This site uses third-party cookies, learn more or accept
dark light

Using the Canvas element to save an image

Written by Max Pelic on

Have you ever wanted to create an image dynamically with JavaScript and give a user the option to download it? You can use this technique to create an image editor, save screenshots from a game, or generate any other images dynamically in the user's browser.

The canvas element allows you to convert the content to a data url, which we can use to download the image. The toDataURL method will return a data URL with the content currently painted on the canvas.

Setting up the canvas

To start, let's create a canvas element and put a blue box on it to make sure it's working:

1<canvas width="500" height="500"></canvas>

2<script>
3let canvas = document.querySelector('canvas'), context = canvas.getContext('2d');
4context.fillStyle = 'blue';
5context.fillRect(20,20,460,460);
6</script>

Download the canvas as an image

Assuming the canvas element is stored in the canvas variable, here's an example of how you can start the download using JavaScript:

1//create a link element

2
let link = document.createElement('a');
3//set the link's href to the canvas data url
4
link.href = canvas.toDataURL('image/png');
5//you can also use 'image/jpeg' to download as a jpeg
6
//set the filename for the download
7
link.setAttribute('download', 'canvas.png');
8//hide the link element
9
link.setAttribute('hidden', 'hidden');
10//append the link to the body so we can click it
11
document.body.appendChild(link);
12//trigger the click function to start the download
13
link.click();

Uses

You can also use this method to:

  • create a download link someone can click on (set the href of the download link as the data url from the canvas)
  • display the content of the canvas as an image (set the image's src attribute to the data url from the canvas)
  • download a frame from a video (use the drawImage method with the video element as the source, and then do the same thing we did before)

Share this article:

Previous Article: Change the color of the URL bar with HTML

Next Article: SQL Conditional Order By