Syntax
js
toBlob(callback)
toBlob(callback, type)
toBlob(callback, type, quality)
Parameters
callback-
A callback function with the resulting
Blobobject as a single argument.nullmay be passed if the image cannot be created for any reason. typeOptional-
A string indicating the image format. The default type is
image/png; that type is also used if the given type isn't supported. qualityOptional-
A
Numberbetween0and1indicating the image quality to be used when creating images using file formats that support lossy compression (such asimage/jpegorimage/webp). A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.
Return value
None (undefined).
Exceptions
SecurityError-
The canvas's bitmap is not origin-clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded.
Examples
Getting a file representing the canvas
Once you have 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.
js
const canvas = document.getElementById("canvas");
canvas.toBlob((blob) => {
const newImg = document.createElement("img");
const url = URL.createObjectURL(blob);
newImg.src = url;
document.body.appendChild(newImg);
});
Note that here we're creating a PNG image; if you add a second parameter to the toBlob() call, you can specify another image type supported by the user agent.
For example, to get the image in JPEG format:
js
canvas.toBlob(
(blob) => {
/* … */
},
"image/jpeg",
0.95,
); // JPEG at 95% quality
Note that we don't immediately revoke the object URL after the image has loaded, because doing so would make the image unusable for user interactions (such as right-clicking to save the image or opening it in a new tab). For long-lived applications, you should revoke object URLs when they're no longer needed (such as when the image is removed from the DOM) to free up memory by calling the URL.revokeObjectURL() method and passing in the object URL string.
Specifications
| Specification |
|---|
| HTML # dom-canvas-toblob-dev |