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:
xxxxxxxxxx
1
var canvas = document.querySelector('#my-canvas');
2
3
var anchor = document.createElement('a');
4
anchor.href = canvas.toDataURL('image/png'); // 'image/jpg'
5
anchor.download = 'image.png'; // 'image.jpg'
6
anchor.click();
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.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<canvas id="my-canvas" width="200" height="200"></canvas>
12
<br>
13
<button onClick="handleClick()">Download image</button>
14
<script>
15
16
var canvas = document.querySelector('#my-canvas');
17
var context = canvas.getContext('2d');
18
19
// Drawing function --------------------------------------------
20
21
function drawSquare(x, y, side) {
22
context.beginPath();
23
context.rect(x, y, side, side); // rect(x, y, width, height)
24
context.fillStyle = 'red';
25
context.fill();
26
}
27
28
drawSquare(50, 50, 100);
29
30
// -------------------------------------------------------------
31
32
// Download canvas (click handler)
33
34
function handleClick() {
35
var anchor = document.createElement('a');
36
anchor.href = canvas.toDataURL('image/png'); // 'image/jpg'
37
anchor.download = 'image.png'; // 'image.jpg'
38
anchor.click();
39
}
40
41
</script>
42
</body>
43
</html>