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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Trending

  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard
  • Grounding AI Agents in Governed Data
  • Nobody Designs an RBAC Mess; Everyone Ends Up With One

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

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
·
Apr. 19, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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