How To Export and Download HTML5 Canvas as an Image
Exporting an HTML5 <canvas> element as an image file (PNG, JPEG, or WebP) is a common requirement for image editors, charting tools, and generative art apps.
There are two primary approaches: the legacy Base64 Data URL method and the modern, memory-efficient Blob / Object URL method.
1. The Modern Method: canvas.toBlob() (Recommended)
For production applications and high-resolution images, canvas.toBlob() is the preferred standard. Unlike toDataURL(), it does not create a massive in-memory Base64 string (~33% size overhead) and will not crash mobile browsers when dealing with large canvases.
/**
* Exports a canvas and triggers an automatic browser file download.
* @param {HTMLCanvasElement} canvas
* @param {string} filename - e.g., 'chart.png'
* @param {'image/png' | 'image/jpeg' | 'image/webp'} type
* @param {number} quality - 0.0 to 1.0 (for JPEG/WebP)
*/
function downloadCanvas(canvas, filename = 'export.png', type = 'image/png', quality = 0.92) {
canvas.toBlob(
(blob) => {
if (!blob) {
console.error('Canvas export failed: blob is null');
return;
}
// Create an object URL representing the binary blob
const url = URL.createObjectURL(blob);
// Create a temporary link and trigger download
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
// Clean up DOM and release memory
document.body.removeChild(link);
URL.revokeObjectURL(url);
},
type,
quality
);
}
Usage
const canvas = document.getElementById('myCanvas');
// Download lossless PNG
downloadCanvas(canvas, 'drawing.png', 'image/png');
// Download compressed JPEG with 80% quality
downloadCanvas(canvas, 'photo.jpg', 'image/jpeg', 0.8);
2. The Simple Method: canvas.toDataURL()
For small canvases or simple thumbnails, toDataURL() synchronously returns a Base64-encoded string:
function downloadCanvasSync(canvas, filename = 'download.png') {
const dataUrl = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.href = dataUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Warning: Never use
toDataURL()for large canvases (e.g. 4K renders) because data URLs hit browser length limits and can cause high memory spikes.
3. Critical Pitfall: The "Tainted Canvas" CORS Error
If you draw an external image onto your canvas from a different domain or CDN:
const img = new Image();
img.src = 'https://external-domain.com/photo.jpg';
ctx.drawImage(img, 0, 0);
canvas.toBlob(...); // THROWS: DOMException: The operation is insecure
Why This Happens
For security reasons, the browser marks a canvas as tainted if cross-origin image data is drawn into it without explicit CORS permissions. Once tainted, calling .toDataURL() or .toBlob() throws an uncatchable security violation to prevent scripts from stealing private user images.
The Fix
- Set
crossOrigin = "anonymous"on the Image element before setting its.src:const img = new Image(); img.crossOrigin = 'anonymous'; // Request CORS headers img.onload = () => { ctx.drawImage(img, 0, 0); }; img.src = 'https://your-cdn.com/photo.jpg'; - Ensure the CDN/Server sends CORS headers:
Access-Control-Allow-Origin: *
4. Crisp Exports on High-DPI (Retina) Displays
By default, an HTML5 canvas rendered on a Retina screen will look blurry when exported unless you scale the internal buffer by window.devicePixelRatio:
function setupHighDpiCanvas(canvas, width, height) {
const dpr = window.devicePixelRatio || 1;
// Set display size (CSS pixels)
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// Scale internal pixel buffer
canvas.width = width * dpr;
canvas.height = height * dpr;
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
return ctx;
}
When calling downloadCanvas(), the exported file will match the true physical pixel resolution.
- How to add content group to Google Analytics
- How To Integrate Google AdSense into Modern Web Apps (React & Next.js)
- How To Export and Download HTML5 Canvas as an Image
- How To Embed YouTube Videos Efficiently (Responsive, Fast & Privacy-Safe)
- How to find all files containing a specific text
- How To Host Static Websites On Amazon AWS EC2
- How To Host Static Websites On Amazon AWS S3
- How To Host Static Websites On GCP Cloud Storage
- How to safely store API Keys
- How to Speed Up IntelliJ IDEA / Clion
- How-to Guides

