3 つの「レイヤー」すべてに描画するには、すべてのレイヤーのコンテキストを作成する必要があります
// references to layer1
var canvas1 = document.getElementById('layer1');
var context1 = canvas1.getContext('2d');
// references to layer2
var canvas2 = document.getElementById('layer2');
var context2 = canvas2.getContext('2d');
// references to layer3
var canvas3 = document.getElementById('layer3');
var context3 = canvas3.getContext('2d');
次に、すべてのレイヤーでの描画が完了したら、それらをマージします (ここでは、layer1 にマージします)。
// merge all layers onto layer1
context1.drawImage(canvas2,0,0);
context1.drawImage(canvas3,0,0);
最後に、マージされたキャンバスを画像に保存し、img src をその画像に設定します。
// save the merged drawings as an image
// and set the img element src to that merged image
var img=new Image();
img.onload=function(){
document.getElementById("results").src=img.src;
}
img.src=canvas1.toDataURL();
ここにコードとフィドルがあります: http://jsfiddle.net/m1erickson/fhjwY/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
// references to layer1
var canvas1 = document.getElementById('layer1');
var context1 = canvas1.getContext('2d');
// references to layer2
var canvas2 = document.getElementById('layer2');
var context2 = canvas2.getContext('2d');
// references to layer3
var canvas3 = document.getElementById('layer3');
var context3 = canvas3.getContext('2d');
// draw stuff on the layers
context1.fillStyle="red";
context2.fillStyle="blue";
context3.fillStyle="green";
context1.fillRect(20,20,50,50);
context2.fillRect(50,50,50,50);
context3.fillRect(80,80,50,50);
// merge all layers onto layer1
context1.drawImage(canvas2,0,0);
context1.drawImage(canvas3,0,0);
// save the merged drawings as an image
// and set the img element src to that merged image
var img=new Image();
img.onload=function(){
document.getElementById("results").src=img.src;
}
img.src=canvas1.toDataURL();
}); // end $(function(){});
</script>
</head>
<body>
<p>Draw rects on 3 canvases</p>
<p>Merge all drawings to 1st canvas</p>
<p>Create an image from merged drawings</p>
<p>Set the image element with that merged image</p>
<canvas id="layer1" width=150 height=150></canvas>
<canvas id="layer2" width=150 height=150></canvas><br>
<canvas id="layer3" width=150 height=150></canvas>
<img id="results" width=150 height=150>
</body>
</html>