EN
JavaScript - capture HTML canvas as png image
0 points
In this article, we would like to show you how to capture HTML canvas as png image using JavaScript.
Quick solution:
xxxxxxxxxx
1
var canvas = document.querySelector('#my-canvas');
2
var image = new Image();
3
image.src = canvas.toDataURL('image/png');
4
document.body.appendChild(image);
In this example, we use toDataURL()
method to get the data URI containing a representation of the canvas
and set it as the src
property of the new image.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
#my-canvas { border: 1px solid gray; }
7
8
</style>
9
</head>
10
<body>
11
<div>Canvas:</div>
12
<canvas id="my-canvas" width="200" height="200"></canvas>
13
<div>Image:</div>
14
<script>
15
16
// Draw rectangles on canvas ----------------------------------------------------
17
18
var canvas = document.querySelector('#my-canvas');
19
var context = canvas.getContext('2d');
20
context.fillStyle = 'red';
21
context.fillRect(20,20,75,75);
22
context.fillStyle = 'blue';
23
context.fillRect(75,75,75,75);
24
25
26
// Capture canvas as png image ---------------------------------------------------
27
28
var image = new Image();
29
image.src = canvas.toDataURL('image/png');
30
document.body.appendChild(image);
31
32
</script>
33
</body>
34
</html>