You can save a canvas as a PNG image using JavaScript by following these steps:
- Get the canvas element.
- Create an anchor element (
<a>
). - Set the href attribute of the anchor element to the canvas image data URI.
- Set the download attribute of the anchor element to the desired file name with the “.png” extension.
- 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.