How to create a downloadable image from an HTML5 canvas.

Written by Thomas Duffy

Intro

Are you looking to save an HTML5 canvas as an image on your computer? It’s actually quite simple to do, and you can even specify the image format and quality. In this blog post, we’ll walk you through the steps to create a downloadable image from an HTML5 canvas using the toDataURL method. You’ll be able to use this technique to save your canvas drawings or exports from other applications (such as image editing software) as image files on your computer. Let’s get started!

To create a downloadable image from an HTML5 canvas, you can use the toDataURL method of the canvas object. This method returns the image data in the form of a base64-encoded data URI. Here’s an example of how you can use toDataURL to create a download link for an image:

<canvas id="myCanvas" width="200" height="100"></canvas>

<a id="downloadLink" download="image.png">Download image</a>

<script>
  // Get the canvas element
  const canvas = document.getElementById('myCanvas');

  // Draw something on the canvas
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = '#FF0000';
  ctx.fillRect(0, 0, 200, 100);

  // Get the data URL of the canvas
  const dataURL = canvas.toDataURL();

  // Set the href attribute of the download link
  const link = document.getElementById('downloadLink');
  link.href = dataURL;
</script>

When you click on the “Download image” link, the browser will prompt you to download the image. The file name of the downloaded image will be “image.png” (you can specify a different file name by changing the download attribute of the link). The image data will be encoded as a PNG image.

You can also specify the image format and quality of the image by passing arguments to the toDataURL method. For example, you can use the following code to create a JPEG image with a quality of 50:

const dataURL = canvas.toDataURL('image/jpeg', 0.5);

Note that the toDataURL method may throw a security error if you try to use it on a canvas that was tainted by cross-origin content. In this case, you will need to use a canvas proxy or CORS headers to allow the canvas to be read from a different origin.

Conclusion

In conclusion, the toDataURL method of the canvas object makes it easy to create a downloadable image from an HTML5 canvas. By using the href attribute of a download link and the download attribute, you can prompt the user to download the image with a custom file name. Additionally, you can specify the image format and quality by passing arguments to the toDataURL method. With these techniques, you can save your canvas drawings or exports as image files on your computer. Happy coding!


Written by Thomas Duffy

Want to Build animations like the one above?

Sign up and get notified when I release my mini course on building animations with React.