How to Save an HTML Canvas as an Image using JavaScript

Updated onbyAlan Morel
How to Save an HTML Canvas as an Image using JavaScript

HTML canvas is a powerful tool for creating graphics and animations.

It can be used to programmatically draw shapes, lines, text, and images on a blank canvas.

A cool thing you can do with a bit of JavaScript is to take the image being rendered on the canvas and download it as an image.

In this post, we'll learn how to take a HTML canvas image and save it as an image file using JavaScript.

How to save a HTML canvas image as an image file

First, we'll create a canvas element and draw a circle on it.

<canvas id="canvas" width="300" height="300"></canvas>
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");

context.beginPath();
context.arc(100, 100, 50, 0, 2 * Math.PI);
context.stroke();

Try it here:

  • HTML
  • JavaScript

Now, we'll create a button that will download the image.

<button id="download">Download</button>

Attach an event listener to the button that will call a function to download the image.

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

download.addEventListener("click", () => {
    // download image
});

Now, this is where the magic happens. The key to downloading the canvas as an image is by first creating an anchor link programmatically.

The goal is to take the canvas data, convert it to a base64 encoded string, and set it as the href attribute of the anchor link.

After that, we can programmatically click the link to download the image.

That looks like this:

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

download.addEventListener("click", () => {
    const link = document.createElement("a");
    link.download = "image.png";
    link.href = canvas.toDataURL();
    link.click();
});

Let's put the whole thing together now:

<canvas id="canvas" width="300" height="300"></canvas>
<button id="download">Download</button>
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");

context.beginPath();
context.arc(100, 100, 50, 0, 2 * Math.PI);
context.stroke();

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

download.addEventListener("click", () => {
    const link = document.createElement("a");
    link.download = "image.png";
    link.href = canvas.toDataURL();
    link.click();
});

That's it! You can now download the image being rendered on the canvas.

Conclusion

In this post, we learned how to take a HTML canvas image and save it as an image file using JavaScript.

Simply create an anchor link, set the href attribute to the base64 encoded string of the canvas, and programmatically click the link to download the image.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.