Canvas How to - Draw canvas as image








Question

We would like to know how to draw canvas as image.

Answer


<!--from w w  w.  j a v a  2 s  . com-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById('grid');
var context = canvas.getContext('2d');
var width = canvas.width,
    height = canvas.height;
context.moveTo(10.5, 10 - 1);
context.lineTo(10.5, 10 + 2);
context.moveTo(10.5 -1, 10.5);
context.lineTo(10.5 +2, 10.5);
context.stroke();
var h=10,
    p=10;
for (i = 0; i < width; i += p) {
    p *= 2;
    context.drawImage(canvas, p, 0);
}
for(i = 0; i < height; i+=h) {
    h *= 2;
    context.drawImage(canvas, 0, h);
}
}//]]>  
</script>
</head>
<body>
  <canvas id="grid" width="500px" height="300px"></canvas>
</body>

The code above is rendered as follows: