jazzgot
jazzgot

Reputation: 419

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

I'm trying to change fillStyle of an path to fully transparent, but instead I get blended colors.

/*****************************
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

How to change path fillStyle? Is it possible to clear not rectangle area of canvas?

Upvotes: 2

Views: 2106

Answers (1)

jazzgot
jazzgot

Reputation: 419

Okey, so here comes simple solution. Big thanks to Kalido.

In my case I could just change globalCompositeOperation value to source-in and then I could change the color (and opacity) instead of blending colors.

Note that you changing this value to whole context so I found quite good practice to set it back to default value after you use it.

My code example:

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

Upvotes: 3

Related Questions