DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Trending

  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • Testing AI-Infused Apps: A Dual-Layer Framework for AI Quality Assurance
  • How to Save Money Using Custom LLMs for Specific Tasks
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial

How To Save HTML Canvas as an Image

Let's look at how to save an HTML Canvas element as an image.

By 
Johnny Simpson user avatar
Johnny Simpson
·
Apr. 19, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.9K Views

Join the DZone community and get the full member experience.

Join For Free

Canvas gives us a lot of flexibility to create great, code generated graphics, and sometimes we need to download them as images. Fortunately, this is quite easy with HTML canvas. Here is an example, where clicking the button downloads the canvas as an image:

Let's look at how this works.

Downloading a Canvas as an Image

In the example above, we've created a canvas image and a button you can click to download it. This button uses toDataURL() to convert our canvas to an image URL data string. When we click on it we get our original canvas, and then create an anchor to download it immediately:

JavaScript
 
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

// Canvas code goes here 
// ...

document.getElementById('download').addEventListener('click', function(e) {
    // Convert our canvas to a data URL
    let canvasUrl = canvas.toDataURL();
    // Create an anchor, and set the href value to our data URL
    const createEl = document.createElement('a');
    createEl.href = canvasUrl;

    // This is the name of our downloaded file
    createEl.download = "download-this-canvas";

    // Click the download button, causing a download, and then remove it
    createEl.click();
    createEl.remove();
});

JavaScript struggles a bit with native downloads, so we are emulating a link click instead. We do that by creating the anchor using createElement, and then using click() to click on it. This achieves the same outcome.

The key thing to remember is to use toDataURL, which encodes our image data as a string that is easily downloaded.

How toDataURL() works

toDataURL() converts a canvas element to a long image encoding string. Let's look at our example:

JavaScript
 
// Convert our canvas to a data URL
let canvasUrl = canvas.toDataURL();
console.log(canvasUrl);
// Outputs 
// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABRQAA...

By default, toDataURL() creates a png image. But fortunately it has options to let us change that if we want.

Saving Images From Canvas as Other Formats

toDataURL(type, encoderOptions) has two arguments which lets us change the way the canvas is encoded. This lets us save files as other formats, such as jpg.

Those two arguments can be defined as follows:

  • type, which is a filetype, in the format image/png.
  • encoderOptions, which is a number between 0 and 1, defining the image quality. This is only supported by file formats that have lossy compression, like webp or jpg.

For example, if we wanted to save our image as a .jpg with a quality of 59%, we could write the following:

JavaScript
 
// Convert our canvas to a data URL
let canvasUrl = canvas.toDataURL("image/jpeg", 0.5);
console.log(canvasUrl);
// Outputs 
// "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAQwAABtbnRyUkdCIFhZWiAAAAAAAAAAAAAAAABhY3NwAAAAAA...

By default, all browsers support image/png. Other formats, like image/jpeg and image/webp are widely supported. Support on image/webp can be found here.

Conclusion

Saving canvas elements as images is straightforward and only relies on toDataURL. If you want to learn about saving canvas images in a real world setting on the backend, you can read my tutorial on that here.

Published at DZone with permission of Johnny Simpson. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook