How to Convert HTML Canvas to PNG Using JavaScript?

Estimated read time 1 min read

To convert an HTML canvas to PNG in JavaScript, you can use the toDataURL() method of the canvas element. The toDataURL() method returns a data URL that represents the contents of the canvas. You can specify the format of the returned data URL using the format argument, where “image/png” indicates a PNG format.

Here’s an example:

var canvas = document.getElementById("canvas");
var pngDataURL = canvas.toDataURL("image/png");

In this example, the canvas element is retrieved using its id attribute and stored in the canvas variable. The toDataURL() method is then called on the canvas variable and the result is stored in the pngDataURL variable. The pngDataURL variable contains the data URL representing the contents of the canvas in PNG format.

This data URL can be used to display the canvas as an image, save it to a file, or send it to a server for further processing. For example, to display the canvas as an image, you can create an <img> element and set its src attribute to the data URL:

var img = document.createElement("img");
img.src = pngDataURL;
document.body.appendChild(img);

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply