How to Convert Canvas to an Image using JavaScript
The HTMLCanvasElement
has special method toDataURL()
which returns a encoded data URI representing the image in the specified format(defaults to PNG).
- If the canvas height or width is 0 or larger than the canvas maximum size, then the string containing
"data:"
is returned. - If the requested type is not
image/png
, but the returned value starts withdata:image/png
, then the requested type is not supported. - Chrome also supports the WEBP(
image/webp
) type.
Syntax:
canvas.toDataURL(type, encoderOptions);
Parameters:
type (optional)
- It indicates the type of image format.
- It will have the value of string type and is an optional parameter with default format type value
image/png
.
encoderOptions (optional)
- It indicates the type of image format.
- It will have the value of number type and is an optional parameter with default value 0.92.
- The value ranges from 0 to 1 indicating the quality of an image to use for formats that use lossy compression such as
image/jpeg
andimage/webp
. - Invalid value is ignored and default value is considered instead of it.
Return value
It returns a DOMString containing the requested data URI.
Example 1
<canvas id="canvas" width="640" height="360"></canvas>
var canvas = document.getElementById('canvas');
var dataURL = canvas.toDataURL();
console.log(dataURL);
/*
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABa...5i/JyZmJr6v77XLtUjciSUnklJd29flKi1cAPKgw"
*/
For more examples visit : How to Convert Canvas to an Image using JavaScript
Hope you learn something new. If this article was helpful, share it.
Happy coding