HTMLCanvasElement

This article is in need of a technical review.

The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of canvas elements. The HTMLCanvasElement interface also inherits the properties and methods of the HTMLElement interface.

Properties

Inherits properties from its parent, HTMLElement.

Name Type Description
height unsigned long Reflects the height HTML attribute, specifying the height of the coordinate space in CSS pixels.
width unsigned long Reflects the width HTML attribute, specifying the width of the coordinate space in CSS pixels.

Methods

Inherits methods from its parent, HTMLElement.

Name & Arguments Return Description
getContext(in DOMString contextId) RenderingContext Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with "2d" returns a CanvasRenderingContext2D object, whereas calling it with "experimental-webgl" (or "webgl") returns a WebGLRenderingContext object. This context is only available on browsers that implement WebGL.
supportsContext() Boolean Returns a Boolean value indicating if the given context is supported by this canvas.
setContext() void Changes the context the element is related to to the given one.
transferControlToProxy() CanvasProxy Gives back a proxy to allow the canvas to be used in another Worker.
toDataURL(in optional DOMString type, in any ...args) DOMString Returns a data: URL containing a representation of the image in the format specified by type (defaults to PNG). The returned image is 96dpi.
  • If the height or width of the canvas is 0, "data:," representing the empty string, is returned.
  • If the type requested is not image/png, and the returned value starts with data:image/png, then the requested type is not supported.
  • Chrome supports the image/webp type.
  • If the requested type is image/jpeg or image/webp, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality; if the second argument is anything else, the default value for image quality is used. Other arguments are ignored.
toDataURLHD() DOMString Returns a data: URL containing a representation of the image in the format specified by type (defaults to PNG). The returned image has the native resolution of the canvas.
  • If the height or width of the canvas is 0, "data:," representing the empty string, is returned.
  • If the type requested is not image/png, and the returned value starts with data:image/png, then the requested type is not supported.
  • Chrome supports the image/webp type.
  • If the requested type is image/jpeg or image/webp, then the second argument, if it is between 0.0 and 1.0, is treated as indicating image quality; if the second argument is anything else, the default value for image quality is used. Other arguments are ignored.
toBlob(in FileCallback callback, in optional DOMString type, in any ...args) void Returns a Blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent. If type is not specified, the image type is image/png. The returned image is 96dpi.
The third argument is used with image/jpeg images to specify the quality of the output.
toBlobHD(in FileCallback callback, in optional DOMString type, in any ...args) void Returns a Blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent. If type is not specified, the image type is image/png. The returned image has the native resolution of the canvas.
mozGetAsFile(in DOMString name, in optional DOMString type) File Returns a File object representing the image contained in the canvas; this file is a memory-based file, with the specified name and. If type is not specified, the image type is image/png.
void mozFetchAsStream(in nsIInputStreamCallback callback, [optional] in DOMString type) void Creates a new input stream that that, when ready, will provide the contents of the canvas as image data. When the new stream is ready, the specified callback's nsIInputStreamCallback.onInputStreamReady() method is called. If type is not specified, the image type is image/png.
Note: This may only be called from chrome code.

Examples

Example: Getting the data-url for a canvas

First do your drawing on the canvas, then call canvas.toDataURL() to get the data: URL for the canvas.

function test() {
 var canvas = document.getElementById("canvas");
 var url = canvas.toDataURL();
 
 var newImg = document.createElement("img");
 newImg.src = url;
 document.body.appendChild(newImg);
}

Example: Getting a file representing the canvas

Once you've drawn content into a canvas, you can convert it into a file of any supported image format. The code snippet below, for example, takes the image in the canvas element whose ID is "canvas", obtains a copy of it as a PNG image, then appends a new <img> element to the document, whose source image is the one created using the canvas.

function test() {
  var canvas = document.getElementById("canvas");
  canvas.toBlob(function(blob) {
    var newImg = document.createElement("img"),
        url = URL.createObjectURL(blob);
    newImg.onload = function() {
      // no longer need to read the blob so it's revoked
      URL.revokeObjectURL(url);
    };
    newImg.src = url;
    document.body.appendChild(newImg);
  });
}

You can use this technique in association with mouse events in order to dynamically change images (grayscale versus color in this example):

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDC Example</title>
<script type="text/javascript">
function showColorImg() {
  this.style.display = "none";
  this.nextSibling.style.display = "inline";
}

function showGrayImg() {
  this.previousSibling.style.display = "inline";
  this.style.display = "none";
}

function removeColors() {
  var aImages = document.getElementsByClassName("grayscale"),
      nImgsLen = aImages.length,
      oCanvas = document.createElement("canvas"),
      oCtx = oCanvas.getContext("2d");
  for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
    oColorImg = aImages[nImgId];
    nWidth = oColorImg.offsetWidth;
    nHeight = oColorImg.offsetHeight;
    oCanvas.width = nWidth;
    oCanvas.height = nHeight;
    oCtx.drawImage(oColorImg, 0, 0);
    oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
    aPix = oImgData.data;
    nPixLen = aPix.length;
    for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
      aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
    }
    oCtx.putImageData(oImgData, 0, 0);
    oGrayImg = new Image();
    oGrayImg.src = oCanvas.toDataURL();
    oGrayImg.onmouseover = showColorImg;
    oColorImg.onmouseout = showGrayImg;
    oCtx.clearRect(0, 0, nWidth, nHeight);
    oColorImg.style.display = "none";
    oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
  }
}
</script>
</head>

<body onload="removeColors();">
<p><img class="grayscale" src="chagall.jpg" alt="" /></p>
</body>
</html>

Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify the image type. For example, to get the image in JPEG format:

 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality
View Live Examples (uses mozGetAsFile())

Specifications

Specification Status Comment
WHATWG HTML Living Standard Living Standard The method getContext() now returns a RenderingContext rather than an opaque object.
The methods supportsContext(), setContext(), transferControlToProxy(), toDataURLHD(), toBlobURLHD() have been added.
HTML5 Candidate Recommendation Initial definition.

Browser support

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (2D context) 4.0 3.6 (1.9.2) 9.0 9.0 [1] 3.1
webgl context 9.0 as experimental-webgl 3.6 (1.9.2) as experimental-webgl
24 (24)
11.0 as experimental-webgl 9.0 as experimental-webgl, behind a user pref.
15.0 as experimental-webgl
5.1 as experimental-webgl
toBlob() Not supported (bug 67587) 18 (18) [2] ? ? Not supported (bug 71270)
toBlobHD(), toDataURLHD(), supportsContext(), setContext(), transferControlToProxy() Not supported Not supported Not supported Not supported Not supported
mozGetAsFile() Not supported 4.0 (2) Not supported Not supported Not supported
mozFetchAsStream() Not supported 13 (13) Not supported Not supported Not supported
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (2D context) 2.1 (Yes) (Yes) ? 10.0 [1] 3.2
webgl context ? ? (Yes) as experimental-webgl ? ? ?
toBlob() Not supported (bug 67587) Not supported (bug 67587) 18.0 (18) [2] ? ? Not supported (bug 71270)
toBlobHD(), toDataURLHD(), supportsContext(), setContext(), transferControlToProxy() Not supported Not supported Not supported Not supported Not supported Not supported
mozGetAsFile() Not supported Not supported 4.0 (2) Not supported Not supported Not supported
mozFetchAsStream() Not supported Not supported 13.0 (13) Not supported Not supported Not supported

[1] Opera Mini 5.0 and later has partial support.

[2] Support for the third parameter, has been added in Gecko 25 only: when used with the "image/jpeg" type, this argument specifies the image quality.

See also

  • HTML element implementing this interface: <canvas>.