2013-07-11 60 views
0

我需要遮擋外部區域,即我在着色器中繪製的形狀被正常繪製,然後對其反色進行陰影處理。其最簡單的例子來說,並指出,工作不到位:Html5 Canvas - 對外部區域進行遮擋

// 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由像素的基礎上,因爲這是緩慢的。必須有某種方式來做到這一點。

回答

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位。

+0

謝謝。那就是訣竅。 – Rewind