我有多个由JavaScript创建的canvas元素。我的问题是:“如何将多个画布元素放到一个画布元素中?”。
答案 0 :(得分:3)
你走了;
只需提供#buffer
画布元素display: none;
,一切都将不可见(请点击此处; 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" />';
}
答案 1 :(得分:2)
画布的drawImage方法实际上可以使用另一个画布而不是图像 - 您不需要首先将画布转换为图像。 (参见WhatWG's documentation。)
我简化了Allendar的JSFiddle来演示:
基本上,您需要做的就是:
targetCanvas.drawImage(sourceCanvas, 0, 0);
你应该好好去。
答案 2 :(得分:0)
也许是这样的,将源画布导出到图像,将该图像绘制到目标画布(未经测试):
function drawCanvasOnOtherCanvas(src, target) {
var img = new Image();
img.onload = function() {
target.drawImage(img, 0, 0);
};
img.src = src.toDataURL('image/png');
}