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"
*/
Examples
<canvas id="canvas" width="640" height="360"></canvas>
function convertCanvasToImage() {
let canvas = document.getElementById("canvas");
let image = new Image();
image.src = canvas.toDataURL();
return image;
}
let pnGImage = convertCanvasToImage();
document.appendChild(pnGImage);
This code will append image element into your browser document.
Different image quality with jpegs format type
var highQuality = canvas.toDataURL("image/jpeg", 1.0);
// "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQ...DVLFP+UpPr5fYpqp1BAEAQBAEB//Z"
var mediumQuality = canvas.toDataURL("image/jpeg", 0.5);
var lowQuality = canvas.toDataURL("image/jpeg", 0.1);
Hope you learn something new. If this article was helpful, share it.
Keep helping and happy 😄 coding