2013-10-22 35 views
4

我試圖繪製多個矩形,然後使用globalCompositeOperation'source-in'屏蔽那些效果很好的問題,但問題是當我填充我的矩形時,它們消失......如果我只有一個fill()調用,它們都可以正確繪製,但只會考慮最後使用的填充樣式。在canvas中使用globalCompositeOperation遮罩多個形狀

代碼中的問題 -

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'下的元素數量是否有限制?還是我錯過了簡單的東西?

這裏有一些小提琴 -

http://jsfiddle.net/ENtXs/ - 但按預期工作不尊重填充樣式。

http://jsfiddle.net/ENtXs/1/ - 卸下面具展現的所有元素

http://jsfiddle.net/ENtXs/2/ - 添加beginPath方法(),並填寫()元素尊重填充樣式。 (無屏蔽)

http://jsfiddle.net/ENtXs/3/ - 添加面具後面(沒有再顯示出來)

http://jsfiddle.net/ENtXs/4/ - 只有具有相同的代碼#3工作正常一個矩形。

+0

這種篡改了一會兒,試着'ctx.globalCompositeOperation'和不同的複合類型....沒什麼。 – inorganik

+0

@inorganik這正是我注意到的。使用不同的填充樣式繪製多個形狀時似乎存在問題。除非有超級簡單的東西,我錯過了...... –

回答

1

解決

我相信這個問題是globalCompositeOperation '源式'。我最終做的是創建一個緩衝區畫布,然後將這些圖像數據繪製到我的主要畫布上,並將GCO應用到該畫布上。

這裏的工作小提琴 - 相關http://jsfiddle.net/ENtXs/5/

代碼:使用`ctx.closePath()`每個形狀後,使用多個口罩和多試過

// 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; 
} 
+0

哇,很好的工作。永遠不會想到這一點。 – inorganik