drawImage
by John Schulz
HTML
<canvas id="two-square-example"></canvas>
<canvas id="put-image-data-example"></canvas>
CSS
canvas { width: 250px; height: 250px; }
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 `drawImage` to render the next 2
var ctx2 = canvas2.getContext('2d')
ctx2.fillStyle = fillColor;
ctx2.strokeStyle = strokeColor;
ctx2.lineWidth = 2;
circle(ctx2, 60, 60, 50);
var img = document.createElement('img');
img.addEventListener( 'load', onDataLoad, false);
img.src = canvas2.toDataURL('image/png');
function onDataLoad( e )
{
var img = e.target;
ctx2.drawImage(img, 30, 10);
ctx2.drawImage(img, 60, 20);
}