globalCompositeOperation对所有图层都有影响吗?

时间:2017-05-07 20:38:04

标签: javascript html5 canvas

我有一个简单的代码,我想为播放器创建掩码。

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.drawImage(level1, 0, 0);
ctx.save();
ctx.fillRect(0,0,mask.width,mask.height);
ctx.globalCompositeOperation="source-in";
ctx.drawImage(hero,0,0);
ctx.restore();

但是globalCompositeOperation影响了backgorund。它认为level1 backround是mask 2。怎样才能解决这个问题?感谢。

1 个答案:

答案 0 :(得分:1)

很难说出你想要的东西。

// clear the whole canvas
ctx.clearRect(0, 0, canvas.width, canvas.height); 
// draw image at top left covering part or all of the canvas
ctx.drawImage(level1, 0, 0);

ctx.save();
// fill part of all of the canvas including the drawn image with black
ctx.fillRect(0,0,mask.width,mask.height);

ctx.globalCompositeOperation="source-in";
//draw image where each pixel in the hero image get the hero colour RGB and the
// source alpha.
ctx.drawImage(hero,0,0);
ctx.restore();

如果面具宽度和高度与画布相同,那么您将看到英雄形象。

也许你想在保持水平图像的同时将英雄形象视为黑色?

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.fillRect(0,0,mask.width,mask.height);
ctx.globalCompositeOperation="destination-in"; 
ctx.drawImage(hero,0,0);
ctx.globalCompositeOperation = "source-over"; // reset default
ctx.drawImage(level1, 0, 0);

如果你想要那个,那么黑​​色英雄像素背后的level1图像

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.fillRect(0,0,mask.width,mask.height);
ctx.globalCompositeOperation="destination-in"; 
ctx.drawImage(hero,0,0);
ctx.globalCompositeOperation="destination-over"; 
ctx.drawImage(level1, 0, 0);
ctx.globalCompositeOperation = "source-over"; // reset default

如果你想要别的东西,你必须多解释一下,或者举例说明你想要的和你得到的东西。

在许多情况下,您无法在一个画布上执行所有合成。在这些情况下,您可以创建第二个屏幕外画布

var offScrCan = document.createElement("canvas");
offScrCan.width = canvas.width;
offScrCan.height = canvas.height;
var ctx1 = offScrCan.getContext("2d");

在屏幕外画布上进行合成,然后在显示画布顶部绘制该画布

ctx.drawImage(offScrCan,0,0);