Saving a Canvas element as an image

Here’s a little tip to allow your users download the contents of a canvas element as an image, without the need for a server. We can do this by using an Anchor tag with a download attribute.

Start with creating <canvas> and <a> tags:

<canvas id="mycanvas"></canvas>
<a href="#" download="MyImage.png" id="downloadlink">Save canvas</a>

The <a> tag’s download attribute can be set to a file name that will be used when saving the file. If no value is specified, it will just be called Download.png.

Next we need to get the contents of the <canvas>, which we can do with JavaScript by calling the toDataURL method of the Canvas element:


1
2
const canvas = document.getElementById("mycanvas");
const canvasdata = canvas.toDataURL(); // gets canvas content as PNG data

Then we can set href of the <a> tag to the canvas data:


1
2
const link = document.getElementById("downloadlink");
link.href = canvasdata;

Now, when the user clicks the link, the browser will ‘download’ the contents at the URL which happens to be a PNG data URI. The downloaded file will have the name specified in the download attribute.

Here is everything together:

HTML

<canvas id="mycanvas"></canvas>
<a href="#" download="MyImage.png" id="downloadlink">Save canvas</a>

JavaScript


1
2
3
4
5
6
const canvas = document.getElementById("mycanvas");
const canvasdata = canvas.toDataURL();

const link = document.getElementById("downloadlink");
link.href = canvasdata;
link.download = "SomeFileName.png";

Hero photo by Lucas Benjamin on Unsplash

Posted toHTML HTML5 Javascript Web Design