JavaScript canvas object method: getContext()
[this page | pdf | back links]
The getContext()
method of the JavaScript
DOM object
corresponding to the HTML <canvas>
element returns an object that can be used to elaborate (populate) the canvas.
It has the following
syntax with the following parameters. It returns a canvas context (or null if
the context type is not recognised.
canvas.getContext(type, attributes)
Parameter
|
Required / Optional
|
Description
|
type
|
Required
|
String representing
type of canvas drawing context. Possible values include:
-
2d
-
webgl
-
webgl2
-
bitmaprenderer
|
attributes
|
Optional
|
A set of additional
attributes that can e.g. help the canvas software. Format is like {alpha: false, … }. Options vary
depending on the context type. For 2d
the only universally recognised attribute is alpha,
indicating if the canvas contains an alpha channel (so if false tells the
browser that the backdrop is always opaque, which can speed up rendering).
For webgl, some other
attributes are acceptable
|
EXAMPLE:
HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span>
<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "100");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");
c2.fillStyle = "blue";
c2.fillRect(10, 10, 180, 80);
document.getElementById("element").appendChild(x2);
</script>
</body>
</html>
|
FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvasGetContext() {
var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.getContext;
} |
NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)