2017-07-18 79 views
-1

我有一張圖像,我用ctx.drawImage繪圖,它具有透明度。我想讓圖像變暗,所以我使用了rgba(0,0,0,0.5)的fillRect,但是也會使圖像的透明部分變暗。所以我正在研究使用ctx.globalCompositeOperation ='atop atop'(包括使用ctx.save和還原),但現在使整個畫布背景變成白色,並且只通過圖像/ fillrect顯示背景。JavaScript canvas使透明圖像更暗

ctx.globalCompositeOperation = '目標之上' 或 '源式' 前:

enter image description here

後:

enter image description here

這裏是我的代碼:

/*above is drawing the background, I only want to merge the fillRect with the drawImage*/ 
ctx.save(); 
ctx.drawImage(o.image, x, y); 
ctx.fillStyle = 'rgba(0,0,0,'+amount+')'; 
ctx.globalCompositeOperation = 'source-in'; 
ctx.fillRect(x, y, w, h); 
ctx.globalCompositeOperation = 'source-over'; 
ctx.restore(); 

回答

1

不確定你在做什麼所以只是猜測。

繪製透明圖像

ctx.globalCompositeOperation = "source-over"; // in case not set 
ctx.drawImage(image,0,0); 

使用 「正片疊底」,以使圖像變暗

ctx.globalCompositeOperation = "multiply" 
ctx.fillStyle = "rgb(128,128,128)"; // dest pixels will darken by 
            // (128/255) * dest 
ctx.fillRect(0,0,image.width,image.height) 

然後恢復阿爾法

ctx.globalCompositeOperation = "destination-in"; 
ctx.drawImage(image,0,0); 

然後恢復默認補償狀態

ctx.globalCompositeOperation = "source-over"; 

一個變暗和圖像的例子。通過上面的方法使左側的圖像變暗。正確的圖像是原始的沒有變暗的圖像。背景顏色是畫布下的顏色。


 
    
 
const ctx = canvas.getContext("2d"); 
 

 
// create an image to darken 
 
const image = document.createElement("canvas"); 
 
image.width = 150; 
 
const ctx1 = image.getContext("2d"); 
 
ctx1.beginPath() 
 
ctx1.fillStyle = "#0F0"; 
 
ctx1.strokeStyle = "#FA0"; 
 
ctx1.lineWidth = 20; 
 
ctx1.arc(75,75,50,0,Math.PI*2); 
 
ctx1.fill(); 
 
ctx1.stroke(); 
 

 
ctx.globalCompositeOperation = "source-over"; // in case not set 
 
ctx.drawImage(image,0,10); 
 
ctx.globalCompositeOperation = "multiply" 
 
ctx.fillStyle = "rgb(128,128,128)"; // dest pixels will darken by 
 
            // (128/255) * dest 
 
ctx.fillRect(0,10,image.width,image.height) 
 
ctx.globalCompositeOperation = "destination-in"; 
 
ctx.drawImage(image,0,10); 
 
ctx.globalCompositeOperation = "source-over"; 
 

 
ctx.font = "16px arial"; 
 
ctx.fillStyle = "black"; 
 
ctx.fillText("Darkened image",10,14); 
 
ctx.drawImage(image,150,10); 
 
ctx.fillText("Original image",160,14);
canvas { border : 2px solid black; }
<canvas id="canvas"></canvas>

如果你已經有了,你將需要使用屏幕外的畫布圖像變暗,然後使用該圖像繪製在畫布在畫布上像素內容。

// create an image to hold darkened copy of image 
const dImage - document.createElement("canvas"); 
dImage.width = image.width; 
dImage.height - image.height; 
const dctx = dImage.getContext("2d"); 
dctx.drawImage(image,0,0); 

// apply darkening to dctx as shown in answer above. 

ctx.drawImage(dImage,0,0); // draws darkened image on canvas 
+0

仍然使背景變白。它會使圖像變暗而不透明,但會使背景變白。也許我應該把這些放在一個新的畫布元素層上。 –

+0

您沒有提供足夠的信息。上面的代碼不能使背景變成白色,因爲「multiply」會使所有像素變暗,而「destination-in」只會影響alpha通道。我將mod的回答使其更清晰 – Blindman67

+0

好吧,我確實說過我正在繪製背景,因爲在fillRect中,您還可以在我的圖像中看到。 –