0

我需要对 OUTSIDE 区域进行着色,即我在着色器中绘制的形状是正常绘制的,然后它们的反面被着色。用一个例子来解释它最容易,并注意不工作的位:

// canvasBackground is the actual background
// canvasBackgroundContext is its context
// To make it simple, I will fill it with green

canvasBackgroundContext.fillStyle = "#00FF00";
canvasBackgroundContext.clearRect(0, 0, canvasBackground.width, canvasBackground.height);

// I also have a the shader
// canvasShader and canvasShaderContext with same width and height as canvasBackground
canvasShaderContext.fillStyle = "rgba(0, 0, 0, 0.25)"; // Black but slightly transparent
canvasShaderContext.clearRect(0, 0, canvasShader.width, canvasShader.height);

// Everything so far is great - now the problem

// This is wrong, because when I create the area I want to create clear, it does not work
// because when you draw a shape it does not work like clearRect, as it does not set each pixel to a clear pixel
canvasShaderContext.fillStyle = "rgba(0, 0, 0, 0.0)";

// Create the only non shaded bits in the shader, overlapping rects
canvasShaderContext.fillRect(10, 10, 50, 50);
canvasShaderContext.fillRect(40, 40, 50, 50);

// So when I do this, it should shade the entire background except for the two 50x50 overlapping rects at 10,10 and 40,40
canvasBackgroundContext.drawImage(canvasShaderContext, 0, 0);

我不想使用 getImageData 逐个像素地进行,因为这很慢。必须有某种方法可以做到这一点。

4

1 回答 1

2

我不确定我是否完全理解您尝试实现的目标,但是如何为此添加复合模式:

canvasShaderContext.fillRect(10, 10, 50, 50);
canvasShaderContext.fillRect(40, 40, 50, 50);

这导致:

/// store old mode whatever that is
var oldMode = canvasShaderContext.globalCompositeOperation;

/// this uses any shape that is drawn next to punch a hole
/// in destination (current context).
canvasShaderContext.globalCompositeOperation = 'destination-out';

/// now draw the holes
canvasShaderContext.fillRect(10, 10, 50, 50);
canvasShaderContext.fillRect(40, 40, 50, 50);

/// set back to old mode
canvasShaderContext.globalCompositeOperation = oldMode;

这也将清除 alpha 位。

于 2013-07-11T22:16:23.123 回答