Export (0) Print
Expand All

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.

The canvas element, Section 4.8.11Internet Explorer 9



var retval = canvas.getContext(contextId, contextAttribute);


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 getContext method returns null if the contextId value is not supported.

Note  A canvas object only supports one context. Additional calls to getContext this object return the same context.

Note  If you are developing on an intranet and have rendering issues for HTML5, you can add a "meta http-equiv-'X-UA-Compatible' content= edge" to the <head> block of a webpage to force Windows Internet Explorer to use the latest standards. You shouldn't use this meta-tag for production webpages. For more information about document compatibility, see Defining Document Compatibility.


The following code example uses getContext to get a context to use to show a 2-D filled rectangle and filled text.

  <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);
<body onload="draw()">
        <canvas id="MyCanvas" width="500" height="500" > </canvas>

See also




© 2015 Microsoft