HTMLCanvasElement

  • Revision slug: DOM/HTMLCanvasElement
  • Revision title: HTMLCanvasElement
  • Revision id: 338503
  • Created:
  • Creator: ttaubert
  • Is current revision? No
  • Comment toBlob() has been implemented.

Revision Content

{{ DomRef() }}

{{ HTMLVersionHeader(5) }}

HTML canvas element interface

DOM canvas elements expose the HTMLCanvasElement interface, which provides properties and methods for manipulating the layout and presentation of canvas elements. The HTMLCanvasElement interface inherits the properties and methods of the {{ domxref("element") }} object interface.

Properties

Name Type Description
height unsigned long Reflects the {{ htmlattrxref("height", "canvas") }} HTML attribute, specifying the height of the coordinate space in CSS pixels.
width unsigned long Reflects the {{ htmlattrxref("width", "canvas") }} HTML attribute, specifying the width of the coordinate space in CSS pixels.

Methods

Name & Arguments Return Description
getContext(in DOMString contextId) object 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. The currently accepted values are "2d" and "experimental-webgl". The "experimental-webgl" context is only available on browsers that implement WebGL. Calling getContext with "2d" returns a CanvasRenderingContext2D Object, whereas calling it with "experimental-webgl" returns a WebGLRenderingContext Object.
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).

  • 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 Function callback, in optional DOMString type, in any ...args) (not implemented in Chromium)

{{ domxref("Blob") }} Returns a {{ domxref("Blob") }} object representing the image contained in the canvas; this file is 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.
mozGetAsFile(in DOMString name, in optional DOMString type) {{ gecko_minversion_inline("2.0") }} {{ non-standard_inline() }} {{ domxref("File") }} Returns a {{ domxref("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 {{ interface("nsIInputStreamCallback") }} callback, [optional] in DOMString type); {{ gecko_minversion_inline("13.0") }} {{ non-standard_inline() }} 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 {{ ifmethod("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.

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);
}

{{ h1_gecko_minversion("Example: Getting a file representing the canvas", "2.0") }}

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 {{ HTMLElement("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

{{ DOMLiveSample("mozGetAsFile.html") }} (uses mozGetAsFile())

Browser support

Browsers will recognize the tag, but more advanced code may not always work the same way.

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 4.0 {{ CompatGeckoDesktop('3.6') }} 9.0 9.0 3.1
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 2.1 {{ CompatVersionUnknown() }} {{ CompatVersionUnknown() }} {{ CompatUnknown() }} 10.0 3.2

(Opera Mini 5.0-6.0 has partial support.)

 

Revision Source

<p>{{ DomRef() }}</p>
<p>{{ HTMLVersionHeader(5) }}</p>
<h2 id="HTML_canvas_element_interface">HTML canvas element interface</h2>
<p>DOM&nbsp;canvas elements expose the <code><a class="external" href="http://www.w3.org/TR/html5/the-canvas-element.html#htmlcanvaselement" rel="external nofollow" target="_blank" title="http://www.w3.org/TR/html5/the-canvas-element.html#htmlcanvaselement">HTMLCanvasElement</a></code> interface, which provides properties and methods for manipulating the layout and presentation of canvas elements. The <code>HTMLCanvasElement</code> interface inherits the properties and methods of the {{ domxref("element") }} object interface.</p>
<h2 id="Properties">Properties</h2>
<table class="standard-table">
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Type</th>
      <th scope="col">Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>height</code></td>
      <td><code>unsigned long</code></td>
      <td>Reflects the {{ htmlattrxref("height", "canvas") }} HTML attribute, specifying the height of the coordinate space in CSS pixels.</td>
    </tr>
    <tr>
      <td><code>width</code></td>
      <td><code>unsigned long</code></td>
      <td>Reflects the {{ htmlattrxref("width", "canvas") }} HTML attribute, specifying the width of the coordinate space in CSS pixels.</td>
    </tr>
  </tbody>
</table>
<h2 id="Methods">Methods</h2>
<table class="standard-table">
  <thead>
    <tr>
      <th scope="col">Name &amp; Arguments</th>
      <th scope="col">Return</th>
      <th scope="col">Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>getContext(in <a href="/en/DOM/DOMString" title="En/DOM/DOMString">DOMString</a> contextId)</code></td>
      <td><code>object</code></td>
      <td>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. The currently accepted values are "2d" and "experimental-webgl". The "experimental-webgl" context is only available on browsers that implement <a href="/en/WebGL" title="En/WebGL">WebGL</a>. Calling getContext with "2d" returns a <code><a href="../../../../en/DOM/CanvasRenderingContext2D" rel="internal">CanvasRenderingContext2D</a></code> Object, whereas calling it with "experimental-webgl" returns a <code>WebGLRenderingContext</code> Object.</td>
    </tr>
    <tr>
      <td><code>toDataURL(in optional <a href="/en/DOM/DOMString" title="En/DOM/DOMString">DOMString</a> type, in any ...args)</code></td>
      <td><code><a href="/en/DOM/DOMString" title="En/DOM/DOMString">DOMString</a></code></td>
      <td>
        <p>Returns a <code>data:</code> URL containing a representation of the image in the format specified by <code>type</code> (defaults to PNG).</p>
        <ul>
          <li>If the height or width of the canvas is 0, <code>"data:,</code>" representing the empty string, is returned.</li>
          <li>If the type requested is not <code>image/png</code>, and the returned value starts with <code>data:image/png</code>, then the requested type is not supported.</li>
          <li>Chrome supports the&nbsp;<code>image/webp&nbsp;</code>type.</li>
          <li>If the requested type is <code>image/jpeg&nbsp;</code>or&nbsp;<code>image/webp</code>, 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.</li>
        </ul>
      </td>
    </tr>
    <tr>
      <td>
        <p><code>toBlob(in </code><code>Function</code><code> callback, in optional&nbsp;</code><code><a href="/en/DOM/DOMString" title="En/DOM/DOMString">DOMString</a></code><code> type, in any ...args) </code>(<a href="http://crbug.com/67587" title="http://crbug.com/67587"><small>not implemented in Chromium</small></a><small>)</small></p>
      </td>
      <td>{{ domxref("Blob") }}</td>
      <td>Returns a {{ domxref("Blob") }} object representing the image contained in the canvas; this file is may be cached on the disk or stored in memory at the discretion of the user agent.&nbsp;If <code>type</code> is not specified, the image type is <code>image/png</code>.</td>
    </tr>
    <tr>
      <td><code>mozGetAsFile(in </code><code><a href="/en/DOM/DOMString" title="En/DOM/DOMString">DOMString</a></code><code> name, in optional&nbsp;</code><code><a href="/en/DOM/DOMString" title="En/DOM/DOMString">DOMString</a></code><code> type)</code> {{ gecko_minversion_inline("2.0") }}&nbsp;{{ non-standard_inline() }}</td>
      <td>{{ domxref("File") }}</td>
      <td>Returns a {{ domxref("File") }} object representing the image contained in the canvas; this file is a memory-based file, with the specified <code>name</code> and. If <code>type</code> is not specified, the image type is <code>image/png</code>.</td>
    </tr>
    <tr>
      <td><code>void mozFetchAsStream(in {{ interface("nsIInputStreamCallback") }} callback, [optional] in DOMString type);</code> {{ gecko_minversion_inline("13.0") }} {{ non-standard_inline() }}</td>
      <td><code>void</code></td>
      <td>
        <p>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 {{ ifmethod("nsIInputStreamCallback", "onInputStreamReady") }} method is called. If <code>type</code> is not specified, the image type is <code>image/png</code>.</p>
        <div class="note">
          <strong>Note:</strong> This may only be called from chrome code.</div>
      </td>
    </tr>
  </tbody>
</table>
<h2 id="Example.3A_Getting_the_data.3A_URL_for_a_canvas">Example: Getting the data: URL for a canvas</h2>
<p>First do your drawing on the canvas, then call <code>canvas.toDataURL()</code> to get the data: URL for the canvas.</p>
<pre class="brush: js">
function test() {
 var canvas = document.getElementById("canvas");
 var url = canvas.toDataURL();
 
 var newImg = document.createElement("img");
 newImg.src = url;
 document.body.appendChild(newImg);
}
</pre>
<p>{{ h1_gecko_minversion("Example: Getting a file representing the canvas", "2.0") }}</p>
<p>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&nbsp;is "canvas", obtains a copy of it as a PNG&nbsp;image, then appends a new {{ HTMLElement("img") }} element to the document, whose source image is the one created using the canvas.</p>
<pre class="brush: js">
function test() {
 var canvas = document.getElementById("canvas");
 canvas.toBlob(function(blob) {
    var newImg = document.createElement("img"),
        url = URL.createObjectURL(blob);
    newImg.onload = function()&nbsp;{
        // no longer need to read the blob so it's revoked
        URL.revokeObjectURL(url);
    };
    newImg.src = url;
    document.body.appendChild(newImg);
 });
}
</pre>
<p>You can use this technique in association with mouse events in order to dynamically change images (grayscale versus color in this example):</p>
<pre class="brush: html">
&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;title&gt;MDC Example&lt;/title&gt;
&lt;script type="text/javascript"&gt;
function showColorImg() {
&nbsp;&nbsp; &nbsp;this.style.display = "none";
&nbsp;&nbsp; &nbsp;this.nextSibling.style.display = "inline";
}

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

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

&lt;body onload="removeColors();"&gt;
&lt;p&gt;&lt;img class="grayscale" src="chagall.jpg" alt="" /&gt;&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Note that here we're creating a PNG&nbsp;image; if you add a second parameter to the <code>toBlob()</code>&nbsp;call, you can specify the image type. For example, to get the image in JPEG format:</p>
<pre class="deki-transform">
 canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95% quality</pre>
<p>{{ DOMLiveSample("mozGetAsFile.html") }} (uses <code>mozGetAsFile()</code>)</p>
<h2 id="Browser_support">Browser support</h2>
<p>Browsers will recognize the tag, but more advanced code may not always work the same way.</p>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Chrome</th>
        <th>Firefox (Gecko)</th>
        <th>Internet Explorer</th>
        <th>Opera</th>
        <th>Safari</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>4.0</td>
        <td>{{ CompatGeckoDesktop('3.6') }}</td>
        <td>9.0</td>
        <td>9.0</td>
        <td>3.1</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="compat-mobile">
  <table class="compat-table">
    <tbody>
      <tr>
        <th>Feature</th>
        <th>Android</th>
        <th>Chrome for Android</th>
        <th>Firefox Mobile (Gecko)</th>
        <th>IE Mobile</th>
        <th>Opera Mobile</th>
        <th>Safari Mobile</th>
      </tr>
      <tr>
        <td>Basic support</td>
        <td>2.1</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>{{ CompatVersionUnknown() }}</td>
        <td>{{ CompatUnknown() }}</td>
        <td>10.0</td>
        <td>3.2</td>
      </tr>
    </tbody>
  </table>
  <p>(Opera Mini 5.0-6.0 has partial support.)</p>
</div>
<p>&nbsp;</p>
Revert to this revision