当在 canvas 上更改路径的 fillStyle 时,颜色实际上混合而不是更改

When changing fillStyle of path on canvas color actually blends not changes

我试图将路径的 fillStyle 更改为完全透明,但我得到的是混合颜色。

/*****************************
ALL BELOW JUST SIMULATING CASE
*****************************/
var c1 = document.getElementById("cool");
var ctx = c1.getContext("2d")

var elem=[0,0,50,0,100,0];
var elem2=[50,0,50,50,50,100];

var i=1;

var path = new Path2D();
path.moveTo(elem[i+1], elem[i+2]);
path.lineTo(elem2[i+1], elem2[i+2]);
path.lineTo(elem2[i-1], elem2[i]);
path.lineTo(elem[i+1], elem[i+2]);
path.closePath();

ctx.fillStyle = getRndColor();
ctx.strokeStyle = ctx.fillStyle;
ctx.fill(path);
ctx.stroke(path);

//this function shouldn't have impact on problem, but i put it here just in case
var getRndColor = function () {
    var r = 255*Math.random()|0,
        g = 255*Math.random()|0,
        b = 255*Math.random()|0;
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}

/*****************************
ALL ABOVE JUST SIMULATING CASE
*****************************/

var changeElement = function(path) {
    ctx.fillStyle = "rgba(0,0,0,0)";
    ctx.strokeStyle = ctx.fillStyle;
    ctx.fill(path);
    ctx.stroke(path);
    console.log(ctx.fillStyle);
}

changeElement(path); //if you try e.g. 50% opacity, you will see that color blends

如何改变路径填充样式?是否可以清除 canvas 的非矩形区域?

好的,简单的解决方案来了。非常感谢 Kalido

在我的例子中,我可以将 globalCompositeOperation 值更改为 source-in,然后我可以更改颜色(和不透明度)而不是混合颜色。

请注意,您将此值更改为整个上下文,因此我发现在使用后将其设置回默认值是一个很好的做法。

我的代码示例:

var changeElement = function(path) {
    ctx.globalCompositeOperation = "source-in";
    ctx.fillStyle = "rgba(0,0,0,0)";
    ctx.strokeStyle = ctx.fillStyle;
    ctx.fill(path);
    ctx.stroke(path);
    ctx.globalCompositeOperation = "source-over"; //setting back to default value to prevent odd behavior of other part of canvas.
}

changeElement(path);