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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Trending

  • The Modern Data Stack Is Overrated — Here’s What Works
  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • A Guide to Container Runtimes

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
DZone Core CORE ·
Apr. 19, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
7.3K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!