An element and API that enables drawing surfaces.

This specification is an experimental breakup of the HTML specification. You can see the full list on the index page and take part in the discussion in the repository.

The canvas element

Categories:
Flow content.
Phrasing content.
Embedded content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Transparent, but with no interactive content descendants except for a elements, img elements with usemap attributes, button elements, input elements whose type attribute are in the Checkbox or Radio Button states, input elements that are buttons, select elements with a multiple attribute or a display size greater than 1, sorting interface th elements, and elements that would not be interactive content except for having the tabindex attribute specified.
Tag omission in text/html:
Neither tag is omissible.
Content attributes:
Global attributes
width — Horizontal dimension
height — Vertical dimension
Allowed ARIA role attribute values:
Any role value.
Allowed ARIA State and Property Attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
typedef (CanvasRenderingContext2D or WebGLRenderingContext) RenderingContext;

interface HTMLCanvasElement : HTMLElement {
  attribute unsigned long width;
  attribute unsigned long height;

  RenderingContext? getContext(DOMString contextId, any... arguments);
  boolean probablySupportsContext(DOMString contextId, any... arguments);

  void setContext(RenderingContext context);
  CanvasProxy transferControlToProxy();

  DOMString toDataURL(optional DOMString type, any... arguments);
  void toBlob(FileCallback? _callback, optional DOMString type, any... arguments);
};

The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.

Authors should not use the canvas element in a document when a more suitable element is available. For example, it is inappropriate to use a canvas element to render a page heading: if the desired presentation of the heading is graphically intense, it should be marked up using appropriate elements (typically h1) and then styled using CSS and supporting technologies such as Web Components.

When authors use the canvas element, they must also provide content that, when presented to the user, conveys essentially the same function or purpose as the canvas' bitmap. This content may be placed as content of the canvas element. The contents of the canvas element, if any, are the element's fallback content.


In interactive visual media, if scripting is enabled for the canvas element, and if support for canvas elements has been enabled, the canvas element represents embedded content consisting of a dynamically created image, the element's bitmap.

In non-interactive, static, visual media, if the canvas element has been previously associated with a rendering context (e.g. if the page was viewed in an interactive visual medium and is now being printed, or if some script that ran during the page layout process painted on the element), then the canvas element represents embedded content with the element's current bitmap and size. Otherwise, the element represents its fallback content instead.

In non-visual media, and in visual media if scripting is disabled for the canvas element or if support for canvas elements has been disabled, the canvas element represents its fallback content instead.

When a canvas element represents embedded content, the user can still focus descendants of the canvas element (in the fallback content). When an element is focused, it is the target of keyboard interaction events (even though the element itself is not visible). This allows authors to make an interactive canvas keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable areas in the fallback content. (Focus has no effect on mouse interaction events.) [[!DOMEVENTS]]

An element whose nearest canvas element ancestor is being rendered and represents embedded content is an element that is being used as relevant canvas fallback content.


The canvas element has two attributes to control the size of the element's bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

The intrinsic dimensions of the canvas element when it represents embedded content are equal to the dimensions of the element's bitmap.

The user agent must use a square pixel density consisting of one pixel of image data per coordinate space unit for the bitmaps of a canvas and its rendering contexts.

A canvas element can be sized arbitrarily by a style sheet, its bitmap is then subject to the 'object-fit' CSS property. [[!CSSIMAGES]]


The bitmaps of canvas elements, as well as some of the bitmaps of rendering contexts, such as those described in the section on the CanvasRenderingContext2D object below, have an origin-clean flag, which can be set to true or false. Initially, when the canvas element is created, its bitmap's origin-clean flag must be set to true.

A canvas bitmap can also have a hit region list, as described in the CanvasRenderingContext2D section below.

A canvas element can have a rendering context bound to it. Initially, it does not have a bound rendering context. To keep track of whether it has a rendering context or not, and what kind of rendering context it is, a canvas also has a canvas context mode, which is initially none but can be changed to either direct-2d, direct-webgl, indirect, or proxied by algorithms defined in this specification.

When its canvas context mode is none, a canvas element has no rendering context, and its bitmap must be fully transparent black with an intrinsic width equal to the numeric value of the element's width attribute and an intrinsic height equal to the numeric value of the element's height attribute, those values being interpreted in CSS pixels, and being updated as the attributes are set, changed, or removed.

When a canvas element represents embedded content, it provides a paint source whose width is the element's intrinsic width, whose height is the element's intrinsic height, and whose appearance is the element's bitmap.

Whenever the width and height content attributes are set, removed, changed, or redundantly set to the value they already have, if the canvas context mode is direct-2d, the user agent must set bitmap dimensions to the numeric values of the width and height content attributes.

The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.


context = canvas . getContext(contextId [, ... ] )

Returns an object that exposes an API for drawing on the canvas. The first argument specifies the desired API, either "2d" or "webgl". Subsequent arguments are handled by that API.

This specification defines the "2d" context below. There is also a specification that defines a "webgl" context. [[!WEBGL]]

Returns null if the given context ID is not supported, if the canvas has already been initialised with the other context type (e.g. trying to get a "2d" context after getting a "webgl" context).

Throws an InvalidStateError exception if the setContext() or transferControlToProxy() methods have been used.

supported = canvas . probablySupportsContext(contextId [, ... ] )

Returns false if calling getContext() with the same arguments would definitely return null, and true otherwise.

This return value is not a guarantee that getContext() will or will not return an object, as conditions (e.g. availability of system resources) can vary over time.

Throws an InvalidStateError exception if the setContext() or transferControlToProxy() methods have been used.

canvas . setContext(context)

Sets the canvas' rendering context to the given object.

Throws an InvalidStateError exception if the getContext() or transferControlToProxy() methods have been used.

There are two ways for a canvas element to acquire a rendering context: the canvas element can provide one via the getContext() method, and one can be assigned to it via the setContext() method. In addition, the whole issue of a rendering context can be taken out of the canvas element's hands and passed to a CanvasProxy object, which itself can then be assigned a rendering context using its setContext() method.

These three methods are mutually exclusive; calling any of the three makes the other two start throwing InvalidStateError exceptions when called.

Each rendering context has a context bitmap mode, which is one of fixed, unbound, or bound. Initially, rendering contexts must be in the unbound mode.


The getContext(contextId, arguments...) method of the canvas element, when invoked, must run the steps in the cell of the following table whose column header describes the canvas element's canvas context mode and whose row header describes the method's first argument.

none direct-2d direct-webgl indirect proxied
"2d" Follow the 2D context creation algorithm defined in the section below, passing it the canvas element and the method's arguments..., to obtain a CanvasRenderingContext2D object; if this does not throw an exception, then set the canvas element's context mode to direct-2d, set the CanvasRenderingContext2D object's context bitmap mode to fixed, and return the CanvasRenderingContext2D object Return the same object as was return the last time the method was invoked with this same first argument. Return null. Throw an InvalidStateError exception. Throw an InvalidStateError exception.
"webgl", if the user agent supports the WebGL feature in its current configuration Follow the instructions given in the WebGL specification's Context Creation section to obtain either a WebGLRenderingContext or null; if the returned value is null, then return null and abort these steps, otherwise, set the canvas element's context mode to direct-webgl, set the new WebGLRenderingContext object's context bitmap mode to fixed, and return the WebGLRenderingContext object [[!WEBGL]] Return null. Return the same object as was return the last time the method was invoked with this same first argument. Throw an InvalidStateError exception. Throw an InvalidStateError exception.
A vendor-specific extension* Behave as defined for the extension. Behave as defined for the extension. Behave as defined for the extension. Throw an InvalidStateError exception. Throw an InvalidStateError exception.
An unsupported value† Return null. Return null. Return null. Throw an InvalidStateError exception. Throw an InvalidStateError exception.

* Vendors may define experimental contexts using the syntax vendorname-context, for example, moz-3d.

† For example, the "webgl" value in the case of a user agent having exhausted the graphics hardware's abilities and having no software fallback implementation.


The probablySupportsContext(contextId, arguments...) method of the canvas element, when invoked, must return false if calling getContext() on the same object and with the same arguments would definitely return null at this time, and true otherwise.


The setContext(context) method of the canvas element, when invoked, must run the following steps:

  1. If the canvas element's canvas context mode is neither none nor indirect, throw an InvalidStateError exception and abort these steps.

  2. If context's context bitmap mode is fixed, then throw an InvalidStateError exception and abort these steps.

  3. If context's context bitmap mode is bound, then run context's unbinding steps and set its context's context bitmap mode to unbound.

  4. Run context's binding steps to bind it to this canvas element.

  5. Set the canvas element's context mode to indirect and the context's context bitmap mode to bound.


url = canvas . toDataURL( [ type, ... ] )

Returns a data: URL for the image in the canvas.

The first argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is image/png; that type is also used if the given type isn't supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.

When trying to use types other than "image/png", authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported. (The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".)

canvas . toBlob(callback [, type, ... ] )

Creates a Blob object representing a file containing the image in the canvas, and invokes a callback with a handle to that object.

The second argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is image/png; that type is also used if the given type isn't supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.

The toDataURL() method must run the following steps:

  1. If the canvas element's bitmap's origin-clean flag is set to false, throw a SecurityError exception and abort these steps.

  2. If the canvas element's bitmap has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero) then return the string "data:," and abort these steps. (This is the shortest data: URL; it represents the empty string in a text/plain resource.)

  3. Let file be a serialisation of the canvas element's bitmap as a file, using the method's arguments (if any) as the arguments.

  4. Return a data: URL representing file. [[!RFC2397]]

The toBlob() method must run the following steps:

  1. If the canvas element's bitmap's origin-clean flag is set to false, throw a SecurityError exception and abort these steps.

  2. Let callback be the first argument.

  3. Let arguments be the second and subsequent arguments to the method, if any.

  4. If the canvas element's bitmap has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero) then let result be null.

    Otherwise, let result be a Blob object representing a serialisation of the canvas element's bitmap as a file, using arguments. [[!FILEAPI]]

  5. Return, but continue running these steps in parallel.

  6. If callback is null, abort these steps.

  7. Queue a task to invoke the FileCallback callback with result as its argument. The task source for this task is the canvas blob serialisation task source.

Proxying canvases to workers

Since DOM nodes cannot be accessed across worker boundaries, a proxy object is needed to enable workers to render to canvas elements in Documents.

[Exposed=(Window,Worker)]
interface CanvasProxy {
  void setContext(RenderingContext context);
};
// CanvasProxy implements Transferable;
canvasProxy = canvas . transferControlToProxy()

Returns a CanvasProxy object that can be used to transfer control for this canvas over to another document (e.g. an iframe from another origin) or to a worker.

Throws an InvalidStateError exception if the getContext() or setContext() methods have been used.

canvasProxy . setContext(context)

Sets the CanvasProxy object's canvas element's rendering context to the given object.

Throws an InvalidStateError exception if the CanvasProxy has been transfered.


The transferControlToProxy() method of the canvas element, when invoked, must run the following steps:

  1. If the canvas element's canvas context mode is not none, throw an InvalidStateError exception and abort these steps.

  2. Set the canvas element's context mode to proxied.

  3. Return a CanvasProxy object bound to this canvas element.

A CanvasProxy object can be neutered (like any Transferable object), meaning it can no longer be transferred, and can be disabled, meaning it can no longer be bound to rendering contexts. When first created, a CanvasProxy object must be neither.

A CanvasProxy is created with a link to a canvas element. A CanvasProxy object that has not been disabled must have a strong reference to its canvas element.

The setContext(context) method of CanvasProxy objects, when invoked, must run the following steps:

  1. If the CanvasProxy object has been disabled, throw an InvalidStateError exception and abort these steps.

  2. If the CanvasProxy object has not been neutered, then neuter it.

  3. If context's context bitmap mode is fixed, then throw an InvalidStateError exception and abort these steps.

  4. If context's context bitmap mode is bound, then run context's unbinding steps and set its context's context bitmap mode to unbound.

  5. Run context's binding steps to bind it to this CanvasProxy object's canvas element.

  6. Set the context's context bitmap mode to bound.

To transfer a CanvasProxy object old to a new owner owner, a user agent must create a new CanvasProxy object linked to the same canvas element as old, thus obtaining new, must neuter and disable the old object, and must finally return new.

Here is a clock implemented on a worker. First, the main page:

<!DOCTYPE HTML>
<title>Clock</title>
<canvas></canvas> 
<script>
  var canvas = document.getElementsByTagName('canvas')[0];
  var proxy = canvas.transferControlToProxy();
  var worker = new Worker('clock.js');
  worker.postMessage(proxy, [proxy]);
</script>

Second, the worker:

onmessage = function (event) {
  var context = new CanvasRenderingContext2D();
  event.data.setContext(context); // event.data is the CanvasProxy object
  setInterval(function () {
    context.clearRect(0, 0, context.width, context.height);
    context.fillText(new Date(), 0, 100);
    context.commit();
  }, 1000);
};

Colour spaces and colour correction

The canvas APIs must perform colour correction at only two points: when rendering images with their own gamma correction and colour space information onto a bitmap, to convert the image to the colour space used by the bitmaps (e.g. using the 2D Context's drawImage() method with an HTMLImageElement object), and when rendering the actual canvas bitmap to the output device.

Thus, in the 2D context, colours used to draw shapes onto the canvas will exactly match colours obtained through the getImageData() method.

The toDataURL() method must not include colour space information in the resources they return. Where the output format allows it, the colour of pixels in resources created by toDataURL() must match those returned by the getImageData() method.

In user agents that support CSS, the colour space used by a canvas element must match the colour space used for processing any colours for that element in CSS.

The gamma correction and colour space information of images must be handled in such a way that an image rendered directly using an img element would use the same colours as one painted on a canvas element that is then itself rendered. Furthermore, the rendering of images that have no colour correction information (such as those returned by the toDataURL() method) must be rendered with no colour correction.

Thus, in the 2D context, calling the drawImage() method to render the output of the toDataURL() method to the canvas, given the appropriate dimensions, has no visible effect.

Serialising bitmaps to a file

When a user agent is to create a serialisation of the bitmap as a file, optionally with some given arguments, and optionally with a native flag set, it must create an image file in the format given by the first value of arguments, or, if there are no arguments, in the PNG format. [[!PNG]]

If the native flag is set, or if the bitmap has one pixel per coordinate space unit, then the image file must have the same pixel data (before compression, if applicable) as the bitmap, and if the file format used supports encoding resolution metadata, the resolution of that bitmap (device pixels per coordinate space units being interpreted as image pixels per CSS pixel) must be given as well.

Otherwise, the image file's pixel data must be the bitmap's pixel data scaled to one image pixel per coordinate space unit, and if the file format used supports encoding resolution metadata, the resolution must be given as 96dpi (one image pixel per CSS pixel).

If arguments is not empty, the first value must be interpreted as a MIME type giving the format to use. If the type has any parameters, it must be treated as not supported.

For example, the value "image/png" would mean to generate a PNG image, the value "image/jpeg" would mean to generate a JPEG image, and the value "image/svg+xml" would mean to generate an SVG image (which would require that the user agent track how the bitmap was generated, an unlikely, though potentially awesome, feature).

User agents must support PNG ("image/png"). User agents may support other types. If the user agent does not support the requested type, it must create the file using the PNG format. [[!PNG]]

User agents must convert the provided type to ASCII lowercase before establishing if they support that type.

For image types that do not support an alpha channel, the serialised image must be the bitmap image composited onto a solid black background using the source-over operator.

If the first argument in arguments gives a type corresponding to one of the types given in the first column of the following table, and the user agent supports that type, then the subsequent arguments, if any, must be treated as described in the second cell of that row.

Arguments for serialisation methods
Type Other arguments Reference
image/jpeg The second argument, if it is a number in the range 0.0 to 1.0 inclusive, must be treated as the desired quality level. If it is not a number or is outside that range, the user agent must use its default value, as if the argument had been omitted. [[!JPEG]]

For the purposes of these rules, an argument is considered to be a number if it is converted to an IDL double value by the rules for handling arguments of type any in the Web IDL specification. [[!WEBIDL]]

Other arguments must be ignored and must not cause the user agent to throw an exception. A future version of this specification will probably define other parameters to be passed to these methods to allow authors to more carefully control compression settings, image metadata, etc.

Security with canvas elements

This section is non-normative.

Information leakage can occur if scripts from one origin can access information (e.g. read pixels) from images from another origin (one that isn't the same).

To mitigate this, bitmaps used with canvas elements are defined to have a flag indicating whether they are origin-clean. All bitmaps start with their origin-clean set to true. The flag is set to false when cross-origin images or fonts are used.

The toDataURL(), toBlob(), and getImageData() methods check the flag and will throw a SecurityError exception rather than leak cross-origin data.

The flag can be reset in certain situations; for example, when a CanvasRenderingContext2D is bound to a new canvas, the bitmap is cleared and its flag reset.