Sometimes, we want to convert HTML5 Canvas to PNG File with JavaScript.
In this article, we’ll look at how to convert HTML5 Canvas to PNG File with JavaScript.
How to convert HTML5 Canvas to PNG File with JavaScript?
To convert HTML5 Canvas to PNG File with JavaScript, we call the toDataURL
method.
For instance, we write
const dlCanvas = (e) => {
const dt = canvas.toDataURL("image/png");
e.target.href = dt.replace(
/^data:image\/[^;]/,
"data:application/octet-stream"
);
};
dl.addEventListener("click", dlCanvas, false);
to define the dlCanvas
.
In it, we call canvas.toDataURL
to return the canvas contents as a base64 string in the format specified by the argument.
Then we call dt.replace
to replace the MIME type part with "data:application/octet-stream"
.
And we set that as the value of href
to start the download.
We call addEventListener
to add a click listener for the dl
link.
Conclusion
To convert HTML5 Canvas to PNG File with JavaScript, we call the toDataURL
method.