The canvas image can be exported using toDataURL() function of canvas object. In JavaScript function. capturecanvas(), a new browser window will be opened with the a bitmap of the canvas captured.
function capturecanvas(){
var mycanvas = document.getElementById("canvas");
window.open(mycanvas.toDataURL(),
"canvasImage",
"left=0," +
"top=0," +
" width=" + mycanvas.width + "," +
"height=" + mycanvas.height);
}
A capture button is add in the HTML, it will call JavaScript function capturecanvas() once clicked.
All HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas</title>
<script type="text/javascript">
function canvasloader(){
var mycanvas = document.getElementById("canvas");
var mycontext = mycanvas.getContext("2d");
mycontext.fillStyle = "#A0A0A0";
mycontext.fillRect(10, 10, 300, 220);
mycontext.fillStyle = "#00ff00";
mycontext.fillRect(20, 20, 200, 100);
mycontext.fillStyle = "#0000ff";
mycontext.fillRect(200, 100, 100, 100);
}
function capturecanvas(){
var mycanvas = document.getElementById("canvas");
window.open(mycanvas.toDataURL(),
"canvasImage",
"left=0," +
"top=0," +
" width=" + mycanvas.width + "," +
"height=" + mycanvas.height);
}
</script>
</head>
<body onload="canvasloader();">
<h1>Hello HTML5 canvas</h1>
<canvas id="canvas" style="border: 1px solid;" width="320" height="240">
Sorry! Your browser doesn't support Canvas.
</canvas>
<form>
<input type="button" id="capture" value="Capture Canvas" onclick="capturecanvas();">
</form>
</body>
</html>