将两个或多个 Canvas 元素与某种混合相结合 [英] Combining two or more Canvas elements with some sort of blending
问题描述
是否可以将 2 个单独的画布元素的内容合并为一个画布元素?
Is it possible to combine the contents of 2 separate canvas elements into a single canvas element?
类似于在 Photoshop 中展平"两个或多个图层的功能......?
Something like an equivalent of 'Flattening' two or more layers in Photoshop...?
我能想到一个方法,但我不太确定.我以 .png 的形式导出两个 Canvi (lol) 的内容,然后让第三个 canvas 元素使用某种混合算法(异或、混合、负片等)绘制两个图像.
I can think of a round about way, but am not so sure about it. I export the contents of both the canvi (lol) in the form of .png's, and then have a third canvas element draw both images with some sort of blending algorithm (xor, blend, negative, etc.).
推荐答案
当然可以,而且你不需要任何有趣的库或任何东西,只需使用画布作为图像调用 drawImage
.
Of course you can, and you don't need any funny libraries or anything, just call drawImage
with a canvas as the image.
这是我将两个画布元素组合到第三个的示例:
Here is an example where I combine two canvas elements onto a third:
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
ctx.fillStyle = 'rgba(255,0,0,.4)';
ctx.fillRect(20, 20, 20, 80);
ctx.fillStyle = 'rgba(205,255,23,.4)';
ctx.fillRect(30, 30, 40, 50);
ctx.fillStyle = 'rgba(5,255,0,.4)';
ctx.fillRect(40, 50, 80, 20);
var can2 = document.getElementById('canvas2');
var ctx2 = can2.getContext('2d');
ctx2.beginPath();
ctx2.fillStyle = "pink";
ctx2.arc(50, 50, 50, 0, Math.PI * 2, 1);
ctx2.fill();
ctx2.beginPath();
ctx2.clearRect(20, 40, 60, 20);
var can3 = document.getElementById('canvas3');
var ctx3 = can3.getContext('2d');
ctx3.drawImage(can, 0, 0);
ctx3.drawImage(can2, 0, 0);
<canvas id="canvas1" width="200" height="200" style="border: 1px solid black"></canvas>
<canvas id="canvas2" width="200" height="200" style="border: 1px solid black"></canvas>
<canvas id="canvas3" width="200" height="200" style="border: 1px solid black"></canvas>
http://jsfiddle.net/bnwpS/878/
当然,你可以只用两个(一个到另一个)来完成,但三个是一个更好的例子.
Of course you can do it with just two (one onto the other), but three makes for a better example.
如果您想要 XOR 效果或其他什么,您可以随时更改 globalCompositeOperation
.
You can always change the globalCompositeOperation
if you want an XOR effect or something.
这篇关于将两个或多个 Canvas 元素与某种混合相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!