Canvas How to - Put image data to canvas








Question

We would like to know how to put image data to canvas.

Answer


<!--from   w ww  .ja  v a2s  .  c om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var canvas = document.getElementById("one");
    var context = canvas.getContext("2d");
    var cw = canvas.width;
    var ch = canvas.height;
    canvas.width = 200;
    canvas.height = 400;
    // Sample graphic
    context.beginPath();
    context.rect(10,10,20,50);
    context.fillStyle = 'yellow';
    context.fill();
    context.lineWidth = 7;
    context.strokeStyle = 'black';
    context.stroke();
    var myImageData = context.getImageData(0, 0, cw, ch);
    context.save();
    context.translate(cw / 2, ch / 2);
    context.putImageData(myImageData, 0, 0);
    context.rotate(0.20);
}//]]>  
</script>
</head>
<body>
  <canvas id="one" width="100" height="200"></canvas>
</body>
</html>

The code above is rendered as follows: