Categories
JavaScript Answers

How to convert HTML5 Canvas to PNG File with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *