Javascript GlobalComposite操作是否影响到所有层?
我有一个简单的代码,我想为玩家创建面具Javascript GlobalComposite操作是否影响到所有层?,javascript,html,canvas,Javascript,Html,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(); 但GlobalCompos
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();
但GlobalComposite的运营影响了水平回退。它认为第1级回传是第2级。如何解决这个问题?谢谢。很难说你想要什么
// 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);
如果你想要,但是黑色英雄像素后面的一级图像
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);