Canvas Layering
Layer canvases and compile them into base64 image
by Jesse M
HTML
<div class="canvas-container">
<canvas id="canv1" width="200" height="200"></canvas>
<canvas id="canv2" width="200" height="200"></canvas>
</div>
<canvas id="newCanv" width="200" height="200"></canvas>
<br />
<button id="screenshot-button">Take Screenshot</button>
<br />
<img src="" id="screenshot-placeholder" />
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica, sans-serif;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
canvas {
width: 200px;
height: 200px;
padding: 0;
}
.canvas-container {
width: 200px;
height: 200px;
display: block;
position: relative;
}
#canv1, #canv2 {
position: absolute;
top: 0;
left: 0;
}
#canv1 {
z-index: 1;
}
#canv2 {
z-index: 2;
}
JavaScript
var canv1 = document.getElementById("canv1"),
ctx = canv1.getContext("2d");
var canv2 = document.getElementById("canv2"),
ctx2 = canv2.getContext("2d");
var newCanv = document.getElementById("newCanv"),
newCtx = newCanv.getContext("2d");
ctx.fillStyle = '#ff0000';
ctx.fillRect(50, 50, 100, 100);
ctx2.fillStyle = '#000';
ctx2.fillRect(75, 75, 50, 50);
// copy canvas content in order, from bottom layer to top layer
// fill abckground of new canvas
newCtx.fillStyle = "#ffffff";
newCtx.fillRect(0, 0, 200, 200);
// draw first canvas content
newCtx.drawImage(canv1, 0, 0);
// draw second canvas content
newCtx.drawImage(canv2, 0, 0);
// take screenshot of combined canvas and set it to an image
$('#screenshot-button').click(function(){
var screenshot = document.getElementById('newCanv').toDataURL();
console.log(screenshot);
$('#screenshot-placeholder').attr('src', screenshot);
});