Reputation: 4676
I have multiple canvas elements created by JavaScript. My question is: "How can I put multiple canvas elements to one canvas element?".
Upvotes: 5
Views: 10554
Reputation:
Here you go;
Just give the #buffer
canvas element display: none;
and everything will happen invisible (check here; http://jsfiddle.net/Allendar/UqxCY/2/).
HTML
<body onload="generatePNG()">
<canvas id="c1"></canvas>
<canvas id="c2"></canvas>
<canvas id="c3"></canvas>
<canvas id="buffer"></canvas>
<div id="output">Empty</div>
</body>
CSS
canvas[id^=c], div[id=output] {
border: 1px solid red;
}
canvas[id=buffer] {
border: 1px dotted green;
}
#output {
padding: 15px;
}
#output img {
border: 1px dotted blue;
}
JavaScript
function generatePNG() {
var b_canvas1 = document.getElementById("c1");
var b_context1 = b_canvas1.getContext("2d");
b_context1.fillRect(10, 50, 50, 50);
var b_canvas2 = document.getElementById("c2");
var b_context2 = b_canvas2.getContext("2d");
b_context2.fillRect(80, 50, 50, 50);
var b_canvas3 = document.getElementById("c3");
var b_context3 = b_canvas3.getContext("2d");
b_context3.fillRect(150, 50, 50, 50);
var img1 = new Image();
img1.src = b_canvas1.toDataURL("image/png");
var img2 = new Image();
img2.src = b_canvas2.toDataURL("image/png");
var img3 = new Image();
img3.src = b_canvas3.toDataURL("image/png");
var buffer = document.getElementById("buffer");
var buffer_context = buffer.getContext("2d");
buffer_context.drawImage(img1, 0, 0);
buffer_context.drawImage(img2, 0, 0);
buffer_context.drawImage(img3, 0, 0);
var buffer_img = new Image();
buffer_img.src = buffer.toDataURL("image/png");
var output = document.getElementById('output');
output.innerHTML = '<img src="' + buffer_img.src + '" alt="Canvas Image" />';
}
Upvotes: 3
Reputation:
A canvas's drawImage method can actually take another canvas instead of an image - you don't need to convert the canvases to images first. (See the WhatWG's documentation.)
I've simplified Allendar's JSFiddle to demonstrate:
Basically, all you need to do is:
targetCanvas.drawImage(sourceCanvas, 0, 0);
and you should be good to go.
Upvotes: 2
Reputation: 27342
Perhaps something like this, export the source canvas to an image, paint that image to the target canvas (untested):
function drawCanvasOnOtherCanvas(src, target) {
var img = new Image();
img.onload = function() {
target.drawImage(img, 0, 0);
};
img.src = src.toDataURL('image/png');
}
Upvotes: 0