Canvas How to - Regenerate image from canvas








Question

We would like to know how to regenerate image from canvas.

Answer


<!--  w w  w  . jav a2s  .c om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    function change_bg_color(val) { 
       document.getElementById('myCanvas').getContext('2d').fillStyle = val;
    }
    var link = document.getElementsByTagName("a")[0];
    link.onclick = function(){
     draw('rgb(200,0,0)');
    }
    var canvas = document.getElementById('myCanvas');
    var context  = canvas.getContext('2d');  
    function draw(val){
            context.fillStyle = val;
            context.fillRect (0, 0, 608, 105);  
            var img = new Image();  
            img.src = 'Round Borders.png';  
            context.drawImage(img,0,0);  
            var dataURL = canvas.toDataURL();
            document.getElementById("canvasImg").src = dataURL;
    }
    draw("rgb(0,200,0)");
});//]]>  
</script>
</head>
<body onmousedown="return false;">
  <canvas id="myCanvas" width="608" height="105" style="display: none;"></canvas>
  <img id="canvasImg" title="Right click to save me!">
  <br />
  <a href="#">change to red</a>
</body>
</html>

The code above is rendered as follows: