How to save canvas as png image?
Here's how you can export a canvas to a PNG. By invoking toDataURL
on the canvas element and creating an anchor (<a>
) tag, set the href
to the data URL. To trigger a download, programmatically click the anchor:
This code directly prompts the download of the canvas content as 'canvas-image.png'.
Complete guide to canvas-to-PNG
The fast answer provides a swift solution, but let's dive deeper and address various nuances, considerations, and exceptions when using toDataURL
operation to save a canvas as a PNG.
Transparency handling in PNG format
PNG format supports transparency which implies any transparent areas in your canvas will remain so in the runtime image. If your application requires a solid background, simply draw one before exporting.
Navigating through cross-browser differences
Different browsers render things differently and have unique security restrictions. Especially when saving a canvas as an image, testing across different browsers and acknowledging issues like Internet Explorer's security settings is a necessity.
Pandora's box: Alternative for older browsers
The API canvas.toBlob()
combined with the saveAs()
function from FileSaver.js offers a workaround in contexts like IE9 where toDataURL
is unsupported:
Forcing a download with MIME types
To auto-download the image file rather than displaying it in the browser, you can change the MIME type to "image/octet-stream"
in the data URL:
Automating downloads: Using download attribute
You can utilize the download
attribute on an anchor tag to suggest a filename and prompt a file download:
Browser security settings: The bane of developers
Some popup blockers or restrictive browser settings might intervene with the window.open
or dynamic link-clicking approach. Always provide alternative instructions for users encountering such issues.
Tips, tricks and workarounds for the pro developer
Having the basics covered, let's dive into some cool advanced techniques and lesser-known tricks:
Saving with dynamic file names
Include the current date and time in the file name to generate unique file names:
Simplified coding with ES6
With modern browsers in play, use ES6 features to simplify your code. Hereβs how:
Event-driven saving magic
Are you looking to trigger the download via an event, like a button click? Wrap the download logic in a function and bind it to the onclick
event:
Was this article helpful?