【问题标题】:canvas overlay export画布叠加导出
【发布时间】:2023-03-21 03:26:01
【问题描述】:
我有 2 个画布,canvas1 和 canvas2。两者都运行良好,但我想将它们混合以导出为图像。基于 CSS 的叠加层不起作用,因为它会打印 2 张图像。有什么要开始的吗?谢谢。
<canvas id="canvas1" style="position:relative; float:left;border:1px solid #000 " width="547" height="154">
</canvas>
<canvas id="canvas2" style="z-index: 1; position:absolute; float:left;" width="547" height="500">
</canvas>
【问题讨论】:
标签:
javascript
html
canvas
html5-canvas
【解决方案1】:
嗯,有几种方法可以解决这个问题,你所说的混合是什么意思?
如果您只是想将 canvas2 覆盖在 canvas1 上,但又不想更改任一原始画布,则可以将其数据发送到另一个画布,然后获取该数据。
方法如下:
draw canvas1 to canvas3
draw canvas2 to canvas3
get canvas3 image
工作的javascript:
// Make all the canvas and context variables */
var c1 = document.getElementById('c1');
var c2 = document.getElementById('c2');
var c3 = document.getElementById('c3');
var c4 = document.getElementById('c4');
var ctx1 = c1.getContext('2d');
var ctx2 = c2.getContext('2d');
var ctx3 = c3.getContext('2d');
var ctx4 = c4.getContext('2d');
/* */
// Draw square on canvas 1
ctx1.fillRect(0,0,50,50);
// Draw offset square on canvas 2
ctx2.fillRect(25,25,50,50);
// Make third image and onload function
var img3 = new Image();
img3.onload = function(){
// Draw this image to canvas 4 so that we know it worked
ctx4.drawImage(this,0,0);
}
// So we know when both have loaded
var imagesLoaded = 0;
function draw(){
// increment number loaded
imagesLoaded++;
// draw this image to canvas 3
ctx3.drawImage(this,0,0);
// if the have both loaded, then...
if (imagesLoaded == 2){
// set third image's src to the canvas 3 image
img3.src = c3.toDataURL();
}
}
// First image
var img1 = new Image();
// So it will draw on canvas 3
img1.onload = draw;
// Set the src to canvas 1's image
img1.src = c1.toDataURL();
// Second image
var img2 = new Image();
// So it will draw on canvas 3
img2.onload = draw;
// Set the src to canvas 2's image
img2.src = c2.toDataURL();
工作示例here。
但是,如果这不是您想要的,我很抱歉。