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

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();
}


这给了我这个样子:



然后,在单击要覆盖其Alpha透明度设置为蓝色的单元格之后,我仍然可以看到原始图像。

模拟如下:



我可以处理点击事件。我需要的是用半透明蓝色覆盖的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,但这不会给我我想要的东西。我怎样才能实现自己想要的?

谢谢

最佳答案

只需使用fillStylergba()设置为透明颜色,然后使用该样式集设置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/

10-10 00:00
查看更多