我正在尝试编写 Sierpinski 地毯前几次迭代的简单演示,如下所示:
我想要继续的方法是通过单击以在每一步上以较小的比例应用基本图案蒙版。在我看来,通过从一个黑色方 block 开始,然后使用“destination-in”的 globalCompositeOperation 和像第二张图像一样的源蒙版,我应该能够做我想做的事,但我很难把它放好在一起。
这会绘制背景黑色方 block :
context.globalCompositeOperation = "source-over";
context.fillStyle = 'black';
context.fillRect(0, 0, 500, 500);
然后我希望像下面这样的代码应该产生第一步。但它只是一片空白。
context.globalCompositeOperation = "destination-in";
var mask = [1, 1, 1, 1, 0, 1, 1, 1, 1];
for (var m = 0; m < 9; ++m)
{
var x = 10 + m % 3 * 150;
var y = 10 + Math.floor(m / 3) * 150;
if (mask[m] > 0)
{
context.fillRect(x, y, 150, 150);
}
}
我在 http://jsfiddle.net/128gxxmy/4/ 整理了一个 fiddle 显示问题。
这似乎真的不是一件难事,所以我显然误解了一些重要的事情,如果有任何建议,我将不胜感激。
谢谢。
编辑:当然!我知道为什么它会变成空白。第一个 fill rect 清除左上角以外的所有内容,下一个将其删除。我需要一次性使用 rect(...) 然后 fill() 。如果我对其进行返工以在单个步骤中绘制每个 channel ,它应该可以解决问题。
最佳答案
为了完整性和防止其他人陷入同样的陷阱,这里是相关代码。我最终使用了一个临时的(不可见的) Canvas ,并用一个填充绘制了整个图层。
function drawLevel(k, fill, mask)
{
tempContext.save();
tempContext.clearRect(0, 0, canvas.width, canvas.height);
// current canvas is destination
tempContext.drawImage(canvas, 0, 0);
// set global composite
tempContext.globalCompositeOperation = "destination-in";
// draw source
tempContext.beginPath();
// how many squares each row
var n = Math.pow(3, k);
var size = 450 / n / 3;
for (var i = 0; i < n; ++i)
for (var j = 0; j < n; ++j)
{
for (var m = 0; m < 9; ++m)
{
var x = 10 + i * size + m % 3 * size;
var y = 10 + j * size + Math.floor(m / 3) * size;
if (mask[m] > 0)
{
tempContext.rect(x, y, size, size);
}
}
}
tempContext.fillStyle = fill;
tempContext.fill();
tempContext.restore();
// copy drawing from tempCanvas onto visible canvas
context.drawImage(tempCanvas, 0, 0);
}
关于javascript - 对 globalCompositeOperation 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983754/