getContext method
Returns an object that provides methods and properties for drawing and manipulating images and graphics on a canvas element in a document. A context object includes information about colors, line widths, fonts, and other graphic parameters that can be drawn on a canvas.
![]() ![]() |
Syntax
var retval = canvas.getContext(contextId, contextAttribute);Parameters
- contextId [in]
-
Type: string
The identifier (ID) of the type of canvas to create.
Internet Explorer 9 and Internet Explorer 10 support only a 2-D context using
canvas.getContext("2d");IE11 also supports 3-D or WebGL context using
canvas.getContext("experimental-webgl"); - contextAttribute [in, optional]
-
IE11 supports an optional set of WebGLContextAttributes for WebGL content. See getContextAttributes for more info.
Return value
Type: CanvasRenderingContext2D
The context object.
Standards information
- The canvas element, Section 4.8.11
Remarks
The getContext method returns null if the contextId value is not supported.
Examples
The following code example uses getContext to get a context to use to show a 2-D filled rectangle and filled text.
<head> <title>getContext example</title> <script type="text/javascript"> function draw() { var canvas = document.getElementById("MyCanvas"); if (canvas.getContext) { var ctx = canvas.getContext("2d"); ctx.font = "italic 36px/2 Unknown Font, sans-serif"; ctx.fillStyle = "blue"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "white"; ctx.fillText("Hello World", canvas.width / 2, canvas.height * .8); } } </script> </head> <body onload="draw()"> <div> <canvas id="MyCanvas" width="500" height="500" > </canvas> </div> </body> </html>
See also

