docs.rodeo

MDN Web Docs mirror

HTMLCanvasElement: getContext() method

{{APIRef("Canvas API")}} 

The HTMLCanvasElement.getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported, or the canvas has already been set to a different context mode.

Later calls to this method on the same canvas element, with the same contextType argument, will always return the same drawing context instance as was returned the first time the method was invoked. It is not possible to get a different drawing context object on a given canvas element.

Syntax

getContext(contextType)
getContext(contextType, contextAttributes)

Parameters

Return value

A rendering context which is either a

If the context identifier is not supported, or the canvas has already been set to a different context mode, null is returned.

Exceptions

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:

const canvas = document.getElementById("canvas");
const 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

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN