Combining canvases
Using 'canvas..context.drawImage()' to paint one canvas into another.
by Brian Peacock
HTML
<div id="box-3">
<div class="box">
<div class="label">Canvas1</div>
<canvas id="c1"></canvas>
</div>
<div class="box">
<div class="label">Canvas2</div>
<canvas id="c2"></canvas>
</div>
<div class="box">
<div class="label">Canvas3</div>
<canvas id="c3"></canvas>
</div>
</div>
<div id="box-2">
<div class="box">
<div class="label">Image1</div>
<img id="image1" src=""/>
</div>
<div class="box">
<div class="label">Image2</div>
<img id="image2" src=""/>
</div>
</div>
CSS
* {
padding:0;
margin:0;
box-sizing:border-box;
}
.label {
width:100%;
margin:0 auto 24px;
clear:both;
display:block;
}
canvas, img {
background-color:#ccc;
border:1px solid #999;
}
canvas {
width:98%;
margin:0 auto;
clear:both;
display:block;
}
#box-2, #box-3 {
width:100%;
height:auto;
text-align:center;
margin:24px auto;
display:block;
}
#box-2 .box, #box-3 .box {
height:auto;
padding:12px;
display:inline-block;
overflow:hidden;
float:left;
}
#box-2 .box {
width:48%
}
#box-3 .box {
width:33%
}
JavaScript
/* simple selector */
var $ = function(a) { return document.getElementById(a.slice(1));}
/* create example canvases */
function exampleCanvas(id, col) {
this.cnv = $(id);
this.ctx = this.cnv.getContext('2d');
this.cnv.width = this.cnv.offsetWidth;
this.cnv.height = this.cnv.width / 2;
this.x = 0;
this.y = this.cnv.height / 2;
this.r = this.cnv.width / 4;
this.col = col;
}
exampleCanvas.prototype.circle = function(X) {
var x = this.cnv.width * X;
this.ctx.fillStyle = this.col;
this.ctx.beginPath();
this.ctx.arc(x, this.y, this.r, 0, Math.PI*2, true);
this.ctx.fill();
};
/* combine canvases */
/* assumes each canvas has the same dimensions */
var overlayCanvases = function(cnv1, cnv2, cnv3) {
var newCanvas = document.createElement('canvas'),
ctx = newCanvas.getContext('2d');
newCanvas.width = cnv1.width;
newCanvas.height = cnv1.height;
[cnv1, cnv2, cnv3].forEach(function(n) {
ctx.beginPath();
ctx.drawImage(n, 0, 0, cnv1.width, cnv1.height);
});
return newCanvas.toDataURL();
};
/* assumes each canvas has the same width */
var verticalCanvases = function(cnv1, cnv2, cnv3) {
var newCanvas = document.createElement('canvas'),
ctx = newCanvas.getContext('2d'),
width = cnv1.width,
height = cnv1.height + cnv2.height + cnv3.height;
newCanvas.width = width;
newCanvas.height = height;
[{
cnv: cnv1,
y: 0
},
{
cnv: cnv2,
y: cnv1.height
},
{
cnv: cnv3,
y: cnv1.height + cnv2.height
}].forEach(function(n) {
ctx.beginPath();
ctx.drawImage(n.cnv, 0, n.y, width, n.cnv.height);
});
return newCanvas.toDataURL();
};
/* run demo */
var canvas1 = new exampleCanvas('#c1','#f00');
var canvas2 = new exampleCanvas('#c2','#ff0');
var canvas3 = new exampleCanvas('#c3','#00f');
canvas1.circle(0.333);
canvas2.circle(0.5);
canvas3.circle(0.666);
/* use return dataURL as image.src */
$('#image1').src = overlayCanvases(canvas1.cnv, canvas2.cnv, canvas3.cnv);
$('#image2').src =...