Categories
JavaScript Answers

How to save canvas as a PNG image with JavaScript?

Spread the love

You can save a canvas as a PNG image using JavaScript by following these steps:

  1. Get the canvas element.
  2. Create an anchor element (<a>).
  3. Set the href attribute of the anchor element to the canvas image data URI.
  4. Set the download attribute of the anchor element to the desired file name with the “.png” extension.
  5. Simulate a click on the anchor element to trigger the download.

For example we write:

function saveCanvasAsPNG(canvas, filename) {
    // Convert the canvas to a data URL
    var dataURL = canvas.toDataURL("image/png");

    // Create a temporary anchor element
    var link = document.createElement("a");
    link.download = filename + ".png";
    link.href = dataURL;

    // Trigger a click on the anchor element to initiate download
    document.body.appendChild(link);
    link.click();

    // Clean up
    document.body.removeChild(link);
}

// Usage example
var canvas = document.getElementById("yourCanvasId");
saveCanvasAsPNG(canvas, "my_canvas_image");

Make sure to replace "yourCanvasId" with the ID of your canvas element and "my_canvas_image" with the desired file name.

Keep in mind that this approach will trigger a download prompt for the user.

If you want to save the image on the server-side, you’ll need to send the data URL to the server and handle the saving process there.

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 *