Javascript Element How to - Create Image from Canvas








Question

We would like to know how to create Image from Canvas.

Answer


<!--from  w w w . jav  a  2 s .  co  m-->
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
canvas {
    border: 1px solid gray;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var can = document.getElementById('canvas1');
    var ctx = can.getContext('2d');
    ctx.fillRect(50,50,50,50);
    var img = new Image();
    img.src = can.toDataURL();
    document.body.appendChild(img);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas1" width="200" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: