Canvas How to - Open canvas output image URL in new window








Question

We would like to know how to open canvas output image URL in new window.

Answer


<!-- w  ww  .  j a  v a 2 s.  c om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var ctx = document.getElementById("canvas").getContext("2d");
    var image = document.getElementById("someImage");
    ctx.fillRect(100,100,100,100);
    image.src = canvas.toDataURL("image/png");
    var link = document.getElementById("link");
    link.addEventListener('click', function(){
        window.open(canvas.toDataURL("image/png"), '_blank');
    });
}//]]>  
</script>
</head>
<body>
  <canvas id="canvas" width="200" height="200"></canvas>
  <img id="someImage"/>
  <button id="link">Link to image</button>
</body>
</html>

The code above is rendered as follows: