JavaScript画布使透明图像更暗

时间:2017-07-18 00:54:30

标签: javascript canvas

我有一个用ctx.drawImage绘制的图像,它有透明度。我想使图像变暗,所以我使用带有rgba(0,0,0,0.5)的fillRect,但这也会使图像的透明部分变暗。所以我正在研究使用ctx.globalCompositeOperation ='destination atop',包括使用ctx.save和restore,但这现在使整个画布背景变白,只显示通过image / fillrect的背景。

在ctx.globalCompositeOperation ='destination atop'或'source-in'之前:

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 个答案:

答案 0 :(得分: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)

然后恢复alpha

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

然后恢复默认的comp状态

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