Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to save HTML Canvas as an Image with canvas.toDataURL()?
The HTML5 Canvas provides the toDataURL() method to export canvas drawings as image data URLs. This method converts the canvas content into a base64-encoded data URL, typically in PNG format, which can be used to save, display, or download the canvas as an image file.
Syntax
Following is the syntax for the toDataURL() method −
canvas.toDataURL(type, encoderOptions)
Parameters
-
type (optional) − A string indicating the image format. Default is
"image/png". Other supported formats include"image/jpeg"and"image/webp". -
encoderOptions (optional) − A number between 0 and 1 indicating image quality for lossy compression formats like JPEG. Default is 0.92.
Return Value
The method returns a data URL string containing the base64-encoded image data. The string starts with data:image/png;base64, followed by the encoded image data.
Basic Canvas to Image Conversion
Example
Following example demonstrates how to draw on a canvas and convert it to a data URL −
<!DOCTYPE html>
<html>
<head>
<title>Canvas to Image Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<canvas id="myCanvas" width="400" height="200" style="border: 1px solid #000;"></canvas>
<br><br>
<button onclick="saveCanvas()">Save as Image</button>
<br><br>
<img id="savedImage" style="border: 1px solid #000;">
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Draw a simple shape
ctx.beginPath();
ctx.arc(200, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#3498db';
ctx.fill();
ctx.strokeStyle = '#2c3e50';
ctx.lineWidth = 3;
ctx.stroke();
// Add text
ctx.font = '20px Arial';
ctx.fillStyle = '#2c3e50';
ctx.textAlign = 'center';
ctx.fillText('Canvas Drawing', 200, 160);
function saveCanvas() {
var dataURL = canvas.toDataURL();
document.getElementById('savedImage').src = dataURL;
}
</script>
</body>
</html>
This example draws a blue circle with text on the canvas. Clicking "Save as Image" converts the canvas to a data URL and displays it as an image below.
Saving Canvas with Different Image Formats
Example − JPEG Format with Quality Control
Following example shows how to save canvas as JPEG with different quality settings −
<!DOCTYPE html>
<html>
<head>
<title>Canvas JPEG Export</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<canvas id="drawCanvas" width="300" height="200" style="border: 1px solid #ccc;"></canvas>
<br><br>
<button onclick="savePNG()">Save as PNG</button>
<button onclick="saveJPEG(0.9)">Save as JPEG (High Quality)</button>
<button onclick="saveJPEG(0.3)">Save as JPEG (Low Quality)</button>
<br><br>
<div id="imageContainer"></div>
<script>
var canvas = document.getElementById('drawCanvas');
var ctx = canvas.getContext('2d');
// Create a gradient background
var gradient = ctx.createLinearGradient(0, 0, 300, 200);
gradient.addColorStop(0, '#ff7675');
gradient.addColorStop(1, '#74b9ff');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 300, 200);
// Add some shapes
ctx.fillStyle = '#fff';
ctx.fillRect(50, 50, 100, 80);
ctx.fillStyle = '#2d3436';
ctx.font = '16px Arial';
ctx.fillText('Sample Text', 60, 95);
function savePNG() {
var dataURL = canvas.toDataURL('image/png');
displayImage(dataURL, 'PNG Format');
}
function saveJPEG(quality) {
var dataURL = canvas.toDataURL('image/jpeg', quality);
var qualityText = quality === 0.9 ? 'High Quality' : 'Low Quality';
displayImage(dataURL, 'JPEG ' + qualityText);
}
function displayImage(dataURL, label) {
var container = document.getElementById('imageContainer');
var div = document.createElement('div');
div.style.marginBottom = '10px';
div.innerHTML = '<p>' + label + ':</p><img src="' + dataURL + '" style="border: 1px solid #ccc;">';
container.appendChild(div);
}
</script>
</body>
</html>
This example demonstrates the difference between PNG (lossless) and JPEG (lossy) formats, showing how quality settings affect file size and image quality.
Downloading Canvas as Image File
Example − Download Canvas Image
Following example shows how to trigger a download of the canvas as an image file −
<!DOCTYPE html>
<html>
<head>
<title>Download Canvas Image</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
<canvas id="artCanvas" width="350" height="250" style="border: 2px solid #34495e;"></canvas>
<br><br>
<button onclick="downloadImage('png')">Download PNG</button>
<button onclick="downloadImage('jpeg')">Download JPEG</button>
<script>
var canvas = document.getElementById('artCanvas');
var ctx = canvas.getContext('2d');
// Create an artistic drawing
ctx.fillStyle = '#ecf0f1';
ctx.fillRect(0, 0, 350, 250);
// Draw multiple colored circles
var colors = ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', '#9b59b6'];
for (var i = 0; i < 5; i++) {
ctx.beginPath();
ctx.arc(70 + i * 60, 125, 30, 0, 2 * Math.PI);
ctx.fillStyle = colors[i];
ctx.fill();
}
// Add title
ctx.fillStyle = '#2c3e50';
ctx.font = 'bold 18px Arial';
ctx.textAlign = 'center';
ctx.fillText('My Canvas Art', 175, 30);
function downloadImage(format) {
var link = document.createElement('a');
var mimeType = format === 'png' ? 'image/png' : 'image/jpeg';
var dataURL = canvas.toDataURL(mimeType, 0.8);
link.download = 'canvas-image.' + format;
link.href = dataURL;
link.click();
}
</script>
</body>
</html>
This example creates a downloadable link that triggers when clicked, allowing users to save the canvas content as either PNG or JPEG files to their device.
Image Format Comparison
Different image formats have specific advantages when saving canvas content −
| Format | Compression | Transparency | Best For |
|---|---|---|---|
| PNG | Lossless | Yes | Graphics with transparency, text, sharp edges |
| JPEG | Lossy | No | Photographs, gradients, smaller file sizes |
| WebP | Lossless/Lossy | Yes | Modern browsers, best compression |
Common Use Cases
-
Image editing applications − Allow users to save their creations as downloadable files.
-
Data visualization − Export charts and graphs generated on canvas as images for reports.
-
Digital signatures − Save signature pad drawings as image files for form submission.
-
Game screenshots − Capture game states or achievements as shareable images.
Conclusion
The toDataURL() method provides a simple way to convert HTML5 canvas content into image data URLs. By specifying different formats and quality options, you can optimize the output for various use cases, from high-quality graphics to compressed web images. This functionality enables powerful image export capabilities in web applications.
