putImageData is a complete jerk

by desandro

HTML

<canvas id="two-square-example" width="200" height="160" style="background: #FF8; 
border: 1px solid #CCC;"> </canvas>
<canvas id="put-image-data-example" width="200" height="160"  style="background: #FF8; 
border: 1px solid #CCC;"> </canvas>

JavaScript

var canvas1 = document.getElementById('two-square-example'),
    canvas2 = document.getElementById('put-image-data-example');

if ( !(canvas1.getContext && canvas1.getContext('2d') ) ) {
  return;
}

var fillColor = 'hsla(0,100%,50%,.4)';
    strokeColor = 'hsla(240,100%,50%,.4)',
    // convienence function for rendering circles
    circle = function( ctx, x, y, radius ) {
      ctx.beginPath();
        ctx.arc ( x, y, radius, 0, Math.PI*2, true);
        ctx.fill();
        ctx.stroke();
      ctx.closePath();
    };

// example 1 renders 3 circles
var ctx1 = canvas1.getContext('2d');
ctx1.fillStyle = fillColor;
ctx1.strokeStyle = strokeColor;
ctx1.lineWidth = 2;
circle( ctx1,  60,  60, 50);
circle( ctx1,  90,  70, 50);
circle( ctx1, 120,  80, 50);

// example 2 renders 1 circle, 
// then uses `putImageData` to render the next 2
var ctx2 = canvas2.getContext('2d')

ctx2.fillStyle = fillColor;
ctx2.strokeStyle = strokeColor;
ctx2.lineWidth = 2;

circle( ctx2,  60,  60, 50);

// limit imgData to 100 x 100 pixels so Firefox can display
var imgData = ctx2.getImageData(0, 0, 100, 100);
ctx2.putImageData( imgData, 30, 10 );
ctx2.putImageData( imgData, 60, 20 );