--- title: HTMLCanvasElement.getContext() slug: Web/API/HTMLCanvasElement/getContext tags: - TV translation_of: Web/API/HTMLCanvasElement/getContext ---
{{APIRef("Canvas API")}}

The HTMLCanvasElement.getContext() method returns a drawing context on the canvas, or {{jsxref("null")}} if the context identifier is not supported.

Later calls to this method on the same canvas element return the same drawing context instance as was returned the last time the method was invoked with the same contextType argument. To get a different drawing context object you need to pass a different contextType or call the method on a different canvas element. 

Syntax

var ctx = canvas.getContext(contextType);
var ctx = canvas.getContext(contextType, contextAttributes);

Parameters

contextType
Is a {{domxref("DOMString")}} containing the context identifier defining the drawing context associated to the canvas. Possible values are:

Note: The identifier "experimental-webgl" is used in new implementations of WebGL. These implementations have either not reached test suite conformance, or the graphics drivers on the platform are not yet stable. The Khronos Group certifies WebGL implementations under certain conformance rules.

contextAttributes

You can use several context attributes when creating your rendering context, for example:

const gl = canvas.getContext('webgl', {
  antialias: false,
  depth: false
});
2d context attributes: WebGL context attributes:

Return value

A {{domxref("RenderingContext")}} which is either a

If the contextType doesn't match a possible drawing context, null is returned.

Examples

Given this {{HTMLElement("canvas")}} element:

<canvas id="canvas" width="300" height="300"></canvas>

You can get a 2d context of the canvas with the following code:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
console.log(ctx); // CanvasRenderingContext2D { ... }

Now you have the 2D rendering context for a canvas and you can draw within it.

Specifications

Specification Status Comment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}} {{Spec2('HTML WHATWG')}} No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "semantics-scripting.html#dom-htmlcanvaselement-getcontext", "HTMLCanvasElement.getContext")}} {{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}} {{Spec2('HTML5 W3C')}} Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.

Browser compatibility

{{Compat("api.HTMLCanvasElement.getContext")}}

See also