gpt4 book ai didi

javascript - 用 Alpha 颜色覆盖 Canvas 图像的一部分

转载 作者:行者123 更新时间:2023-12-02 16:16:04 25 4
gpt4 key购买 nike

我正在使用 Canvas 控件。我将图像加载到其中:

var cn1 = document.getElementById('canvas1');
cn1.addEventListener("mousedown", getPosition, false);

var context = cn1.getContext('2d');
var width = 360;
var height = 240
cn1.width = 360;
cn1.height = 240;
var imageObj = new Image();

imageObj.onload = function () {
context.drawImage(imageObj, 0, 0, width, height);
DrawLines();
};
imageObj.src = '/Images/7.jpg';

然后我使用以下方法覆盖一些网格线:

function DrawLines()
{
context.beginPath();
for (var x = 0; x < 361; x = x + 24) {
context.moveTo(x, 0);
context.lineTo(x, 0);
context.lineTo(x, 240);
}
for (var y = 0; y < 241; y = y + 24) {
context.moveTo(0, y);
context.lineTo(0, y);
context.lineTo(360, y);
}
context.lineWidth = 1;
context.strokeStyle = '#FC5C5C';
context.stroke();
context.closePath();
}

这给了我这样的外观:

enter image description here

然后,单击一个单元格后,我想用蓝色覆盖并设置其 alpha 透明度,以便用户仍然可以看到原始图像。

这个模型看起来像:

enter image description here

我可以处理点击事件。我需要的是 JavaScript 来覆盖我的半透明蓝色。

我在 StackOverFlow 上找到了这个:

// Loops through all of the pixels and modifies the components.
for (var i = 0, n = pix.length; i <n; i += 4) {
pix[i] = uniqueColor[0]; // Red component
pix[i+1] = uniqueColor[1]; // Green component
pix[i+2] = uniqueColor[2]; // Blue component
//pix[i+3] is the transparency.
}
ctx.putImageData(imgd, 0, 0);

从此链接:Another example但这不会给我我想要的。我怎样才能实现我想要的?

谢谢

最佳答案

只需使用 rgba()fillStyle 设置为透明颜色,然后使用该样式集 fillRect() 即可。

使用 getImageData/putImageData 是可能的,但速度较慢,并且需要满足 CORS,以防图像从与页面不同的来源加载。

您可以执行以下操作:

context.fillStyle = "rgba(150,150,255, 0.3)";  // last value is alpha [0.0, 1.0]
context.fillRect(x, y, w, h);

提示:您还可以将网格线代码减少为:

context.moveTo(x, 0);
//context.lineTo(x, 0); not needed here
context.lineTo(x, 240);

关于javascript - 用 Alpha 颜色覆盖 Canvas 图像的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29580445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com