Javascript 在画布中使用GlobalComposite操作屏蔽多个形状

Javascript 在画布中使用GlobalComposite操作屏蔽多个形状,javascript,canvas,globalcompositeoperation,Javascript,Canvas,Globalcompositeoperation,我正在尝试绘制多个矩形,然后使用globalCompositeOperation“source in”屏蔽这些矩形,这非常有效,但问题是当我填充矩形时,它们会消失。。。如果我只有一个fill()调用,它们都会正确绘制,但只尊重应用的最后一个填充样式 有关守则- ctx.drawImage(self.glass.mask, 256, 375); ctx.globalCompositeOperation = 'source-in'; ctx.rect(256, 635, 256, 75); ctx

我正在尝试绘制多个矩形,然后使用globalCompositeOperation“source in”屏蔽这些矩形,这非常有效,但问题是当我填充矩形时,它们会消失。。。如果我只有一个fill()调用,它们都会正确绘制,但只尊重应用的最后一个填充样式

有关守则-

ctx.drawImage(self.glass.mask, 256, 375);
ctx.globalCompositeOperation = 'source-in';

ctx.rect(256, 635, 256, 75);
ctx.fillStyle = "#c65127";

ctx.rect(256, 605, 256, 25);
ctx.fillStyle = "#f5f4f0";

ctx.rect(256, 565, 256, 35);
ctx.fillStyle = "#c65127";

ctx.fill();
上面的代码工作正常。但如果我这么做了,摘下面具-

ctx.beginPath();
ctx.rect(0, 256, 256, 75);
ctx.fillStyle = "#c65127";
ctx.fill();

ctx.beginPath();
ctx.rect(0, 226, 256, 25);
ctx.fillStyle = "#f5f4f0";
ctx.fill();

ctx.beginPath();
ctx.rect(0, 186, 256, 35);
ctx.fillStyle = "#222";
ctx.fill();
我有每个矩形,他们尊重他们的填充样式。问题是当我启用遮罩时,它们不再可见

在globalCompositeOperation“source in”下,您可以拥有的元素数量是否有限制,或者我只是缺少了一些简单的元素

这里有一些小提琴-

-按预期工作,但不遵守填充样式

-移除遮罩以显示所有元素

-添加beginPath()和fill()元素时会考虑填充样式。(无遮罩)

-重新添加遮罩(不再显示任何内容)


-只有一个与#3代码相同的矩形才能正常工作。

已解决

我认为问题在于globalCompositeOperation的“源代码输入”。我最后做的是创建一个缓冲画布,在上面绘制形状,然后将图像数据绘制到我的主画布中,并应用GCO

这是一把小提琴-

有关守则:

// Canvas and Buffers
var canvas = document.getElementById('canvas');
var buffer = document.getElementById('buffer');
var ctx = canvas.getContext('2d');
var buffer_ctx = buffer.getContext('2d');

// sizing
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;

buffer.height = window.innerHeight;
buffer.width = window.innerWidth;

// mask image
var mask = new Image();
mask.onload = function () {
    drawBuffer();
}

mask.src = 'http://drewdahlman.com/experiments/masking/highball_mask.png';

function drawBuffer() {
    buffer_ctx.beginPath();
    buffer_ctx.rect(0, 256, 256, 75);
    buffer_ctx.fillStyle = "#c65127";
    buffer_ctx.fill();

    buffer_ctx.beginPath();
    buffer_ctx.rect(0, 226, 256, 25);
    buffer_ctx.fillStyle = "#f5f4f0";
    buffer_ctx.fill();

    buffer_ctx.beginPath();
    buffer_ctx.rect(0, 186, 256, 35);
    buffer_ctx.fillStyle = "#222";
    buffer_ctx.fill();

    var image = buffer.toDataURL("image/png");
    var img = new Image();
    img.onload = function(){
        buffer_ctx.clearRect(0,0,buffer.width,buffer.height);
        ctx.drawImage(mask,0,0);
        ctx.globalCompositeOperation = 'source-in';
        ctx.drawImage(img,0,0);
    }
    img.src = image;
}

对此进行了一段时间的篡改,尝试在每个形状后使用
ctx.closePath()
,尝试使用多个遮罩和多个
ctx.globalCompositeOperation
和不同的复合类型。。。。没什么。@inorganik这正是我注意到的。似乎在使用不同的填充样式绘制多个形状时存在问题。除非我遗漏了一些非常简单的东西。。。。