← 4.8.6 The video elementTable of contents4.8.11 The map element →
      1. 4.8.10 The canvas element
        1. 4.8.10.1 Color spaces and color correction
        2. 4.8.10.2 Security with canvas elements

4.8.10 The canvas element

ISSUE-74 (canvas-accessibility) blocks progress to Last Call

Categories
Flow content.
Phrasing content.
Embedded content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Transparent.
Content attributes:
Global attributes
width
height
DOM interface:
interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;

  DOMString toDataURL(in optional DOMString type, in any... args);

  object getContext(in DOMString contextId, in any... args);
};

The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, 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 XBL.

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 bitmap canvas. 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.

In non-interactive, static, visual media, if the canvas element has been previously painted on (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 current image 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). This allows authors to make an interactive canvas keyboard-focusable: authors should have a one-to-one mapping of interactive regions to focusable elements in the fallback content. <ZZZ> Descendant elements which require initialization (e.g. img and iframe) shall not be initialized on page load. </ZZZ>

The canvas element has two attributes to control the size of the coordinate space: 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 equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

The size of the coordinate space does not necessarily represent the size of the actual bitmap that the user agent will use internally or during rendering. On high-definition displays, for instance, the user agent may internally use a bitmap with two device pixels per unit in the coordinate space, so that the rendering remains at high quality throughout.

When the canvas element is created, and subsequently whenever the width and height attributes are set (whether to a new value or to the previous value), the bitmap and any associated contexts must be cleared back to their initial state and reinitialized with the newly specified coordinate space dimensions.

When the canvas is initialized, its bitmap must be cleared to transparent black.

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

Only one square appears to be drawn in the following example:

  // canvas is a reference to a <canvas> element
  var context = canvas.getContext('2d');
  context.fillRect(0,0,50,50);
  canvas.setAttribute('width', '300'); // clears the canvas
  context.fillRect(0,100,50,50);
  canvas.width = canvas.width; // clears the canvas
  context.fillRect(100,0,50,50); // only this square remains

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

Returns an object that exposes an API for drawing on the canvas. The first argument specifies the desired API. Subsequent arguments are handled by that API.

The list of defined contexts is given on the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]

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

A canvas element can have a primary context, which is the first context to have been obtained for that element. When created, a canvas element must not have a primary context.

The getContext(contextId, args...) method of the canvas element, when invoked, must run the following steps:

  1. Let contextId be the first argument to the method.

  2. If contextId is not the name of a context supported by the user agent, return null and abort these steps.

  3. If the element has a primary context and that context's entry in the WHATWG Wiki CanvasContexts page does not list contextId as a context with which it is compatible, return null and abort these steps. [WHATWGWIKI]

  4. If the element does not have a primary context, let the element's primary context be contextId.

  5. If the getContext() method has already been invoked on this element for the same contextId, return the same object as was returned that time, and abort these steps. The additional arguments are ignored.

  6. Return a new object for contextId, as defined by the specification given for contextId's entry in the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]

New context types may be registered in the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]

Anyone is free to edit the WHATWG Wiki CanvasContexts page at any time to add a new context type. These new context types must be specified with the following information:

Keyword

The value of contextID that will return the object for the new API.

Specification

A link to a formal specification of the context type's API. It could be another page on the Wiki, or a link to an external page. If the type does not have a formal specification, an informal description can be substituted until such time as a formal specification is available.

Compatible with

The list of context types that are compatible with this one (i.e. that operate on the same underlying bitmap). This list must be transitive and symmetric; if one context type is defined as compatible with another, then all types it is compatible with must be compatible with all types the other is compatible with.

Vendors may also define experimental contexts using the syntax vendorname-context, for example, moz-3d. Such contexts should be registered in the WHATWG Wiki CanvasContexts page.


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.

The toDataURL() method must, when called with no arguments, return a data: URL containing a representation of the image as a PNG file. [PNG]

If the canvas has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero) then the method must return the string "data:,". (This is the shortest data: URL; it represents the empty string in a text/plain resource.)

When the toDataURL(type) method is called with one or more arguments, it must return a data: URL containing a representation of the image in the format given by type. The possible values are MIME types with no parameters, for example image/png, image/jpeg, or even maybe image/svg+xml if the implementation actually keeps enough information to reliably render an SVG image from the canvas.

For image types that do not support an alpha channel, the image must be composited onto a solid black background using the source-over operator, and the resulting image must be the one used to create the data: URL.

Only support for image/png is required. User agents may support other types. If the user agent does not support the requested type, it must return the image using the PNG format.

User agents must convert the provided type to ASCII lowercase before establishing if they support that type and before creating the data: URL.

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:,".)

If the method is invoked with the first argument giving 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.

Type Other arguments
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.

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 raise an exception. A future version of this specification will probably define other parameters to be passed to toDataURL() to allow authors to more carefully control compression settings, image metadata, etc.

4.8.10.1 Color spaces and color correction

The canvas APIs must perform color correction at only two points: when rendering images with their own gamma correction and color space information onto the canvas, to convert the image to the color space used by the canvas (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, colors used to draw shapes onto the canvas will exactly match colors obtained through the getImageData() method.

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

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

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

4.8.10.2 Security with canvas elements

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, canvas elements are defined to have a flag indicating whether they are origin-clean. All canvas elements must start with their origin-clean set to true. The flag must be set to false if any of the following actions occur:

Whenever the toDataURL() method of a canvas element whose origin-clean flag is set to false is called, the method must raise a SECURITY_ERR exception.

Whenever the getImageData() method of the 2D context of a canvas element whose origin-clean flag is set to false is called with otherwise correct arguments, the method must raise a SECURITY_ERR exception.

Even resetting the canvas state by changing its width or height attributes doesn't reset the origin-clean flag.