Subscribe

Vanilla JavaScript save canvas as an image

✍️

Guide explaining how exporting our Canvas drawing as an image to download. Try the Codepen to see yourself.

15 Sep, 2020 Β· 2 min read

Yesterday, we started our introductory canvas course.

In this JavaScript tutorial, we will learn how to save the canvas as an image and download it.

So how do we convert the canvas to export it as an image?

There are two ways of doing this. And we will explore both.

Live Code example in Codepen

See the Pen Vanilla JavaScript save canvas as image by Chris Bongers (@rebelchris) on CodePen.

1. Canvas to Image with Right-click to save

Everyone knows this option, but we can just right-click on the canvas to save as image.

This will only work in specific browsers. That's why it's not the most valid way of saving the image.

Canvas save to image right click

Note: Keep in mind the canvas has no background!

2. Download button to save an image from the canvas

The second solution is to add a download button to our page. The button will then export the canvas content and open the base64 image in another tab. And from there you can download the image.

Add the download button.

<canvas id="canvas" height="200"></canvas>
<br />
<button id="download">Download</button>

Now let's add the button variable to our JavaScript code:

const download = document.getElementById('download');

Awesome. We need to add an eventListener to it and listen to the click command.

download.addEventListener('click', function (e) {
  const link = document.createElement('a');
  link.download = 'download.png';
  link.href = canvas.toDataURL();
  link.click();
  link.delete;
});

We create a temporary link href on which we will place the canvas's data URL and then click it.

We are using the toDataURL function, which returns a base64 image string that looks something like this:

// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"

Browser Support

The canvas element is well supported these days and is defiantly a good option if you want to draw vectors on screen.

Browser support HTML canvas

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

TypeORM viewEntity

30 Mar, 2022 Β· 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 Β· 3 min read

The Record Utility Type in TypeScript

Join 1371 devs and subscribe to my newsletter