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

Using the Canvas element to save an image

Use the toDataURL method to download the content of a canvas element onto the user's computer.
Written by Maxwell Pelic,

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:


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

<script>

let canvas = document.querySelector('canvas'), context = canvas.getContext('2d');

context.fillStyle = 'blue';

context.fillRect(20,20,460,460);

</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:


//create a link element

let link = document.createElement('a');

//set the link's href to the canvas data url

link.href = canvas.toDataURL('image/png'); 

//you can also use 'image/jpeg' to download as a jpeg

//set the filename for the download

link.setAttribute('download', 'canvas.png');

//hide the link element

link.setAttribute('hidden', 'hidden');

//append the link to the body so we can click it

document.body.appendChild(link);

//trigger the click function to start the download

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)

Previous Article: Dark/Light mode - HTML and CSS, JavaScript if you'd like

Next Article: Moving away from AMP