EN
JavaScript - download canvas as png/jpg file on click
0
points
In this article, we would like to show you how to download canvas as .png
or .jpg
file on the button click event using JavaScript.
Quick solution:
var canvas = document.querySelector('#my-canvas');
var anchor = document.createElement('a');
anchor.href = canvas.toDataURL('image/png'); // 'image/jpg'
anchor.download = 'image.png'; // 'image.jpg'
anchor.click();
Practical example
In this example, we create an invisible anchor (a
) element with href
property set to the data URL containing a representation of the image on the canvas. Using the download
property, we specify the file name to be downloaded. Then we invoke the download with the click()
method.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
#my-canvas { border: 1px solid gray; }
</style>
</head>
<body>
<canvas id="my-canvas" width="200" height="200"></canvas>
<br>
<button onClick="handleClick()">Download image</button>
<script>
var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
// Drawing function --------------------------------------------
function drawSquare(x, y, side) {
context.beginPath();
context.rect(x, y, side, side); // rect(x, y, width, height)
context.fillStyle = 'red';
context.fill();
}
drawSquare(50, 50, 100);
// -------------------------------------------------------------
// Download canvas (click handler)
function handleClick() {
var anchor = document.createElement('a');
anchor.href = canvas.toDataURL('image/png'); // 'image/jpg'
anchor.download = 'image.png'; // 'image.jpg'
anchor.click();
}
</script>
</body>
</html>