2017-05-07 93 views
0

我有一個簡單的代碼,我想爲玩家創建面具。globalCompositeOperation是否影響到所有圖層?

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.drawImage(level1, 0, 0); 
ctx.save(); 
ctx.fillRect(0,0,mask.width,mask.height); 
ctx.globalCompositeOperation="source-in"; 
ctx.drawImage(hero,0,0); 
ctx.restore(); 

但globalCompositeOperation受影響的水平backgorund。它認爲level1背景是掩碼兩。這個問題怎麼解決?謝謝。

回答

1

很難說出你想要的。

// clear the whole canvas 
ctx.clearRect(0, 0, canvas.width, canvas.height); 
// draw image at top left covering part or all of the canvas 
ctx.drawImage(level1, 0, 0); 

ctx.save(); 
// fill part of all of the canvas including the drawn image with black 
ctx.fillRect(0,0,mask.width,mask.height); 

ctx.globalCompositeOperation="source-in"; 
//draw image where each pixel in the hero image get the hero colour RGB and the 
// source alpha. 
ctx.drawImage(hero,0,0); 
ctx.restore(); 

如果遮罩的寬度和高度與畫布相同,那麼您只會看到英雄圖像。

也許你想只是英雄形象爲黑色,同時保持關卡圖像?

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.fillRect(0,0,mask.width,mask.height); 
ctx.globalCompositeOperation="destination-in"; 
ctx.drawImage(hero,0,0); 
ctx.globalCompositeOperation = "source-over"; // reset default 
ctx.drawImage(level1, 0, 0); 

如果你想如此,但黑英雄像素後面的1級圖像

ctx.clearRect(0, 0, canvas.width, canvas.height); 
ctx.fillRect(0,0,mask.width,mask.height); 
ctx.globalCompositeOperation="destination-in"; 
ctx.drawImage(hero,0,0); 
ctx.globalCompositeOperation="destination-over"; 
ctx.drawImage(level1, 0, 0); 
ctx.globalCompositeOperation = "source-over"; // reset default 

如果你想要的東西,否則你將不得不解釋多一點,或給你想要什麼的示例圖像和你得到什麼。

有許多情況下,您無法在一個畫布上進行所有合成。在這些情況下,您創建第二個屏幕外的畫布

var offScrCan = document.createElement("canvas"); 
offScrCan.width = canvas.width; 
offScrCan.height = canvas.height; 
var ctx1 = offScrCan.getContext("2d"); 

執行關閉屏幕畫布上的合成,然後繪製畫布上顯示畫布

ctx.drawImage(offScrCan,0,0); 
+0

非常感謝你的頂部,這個代碼固定我問題。 – Anonymous