JavaScript canvas使透明图像更暗
问题描述:
我有一张图像,我用ctx.drawImage绘图,它具有透明度。我想让图像变暗,所以我使用了rgba(0,0,0,0.5)的fillRect,但是也会使图像的透明部分变暗。所以我正在研究使用ctx.globalCompositeOperation ='atop atop'(包括使用ctx.save和还原),但现在使整个画布背景变成白色,并且只通过图像/ fillrect显示背景。JavaScript canvas使透明图像更暗
ctx.globalCompositeOperation = '目标之上' 或 '源式' 前:
后:
这里是我的代码:
/*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();
答
不确定你在做什么所以只是猜测。
绘制透明图像
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
仍然使背景变白。它会使图像变暗而不透明,但会使背景变白。也许我应该把这些放在一个新的画布元素层上。 –
您没有提供足够的信息。上面的代码不能使背景变成白色,因为“multiply”会使所有像素变暗,而“destination-in”只会影响alpha通道。我将mod的回答使其更清晰 – Blindman67
好吧,我确实说过我正在绘制背景,因为在fillRect中,您还可以在我的图像中看到。 –