Search code examples
javascriptcanvas

JS Canvas fillStyle works incorrectly


fillStyle doesn't work properly with:

function draw_grd (x,y,r,c1,c2) {
    var gradient = ctx.createRadialGradient(x, y, 0, x, y, r);
    gradient.addColorStop(0,c1);
    gradient.addColorStop(1,c2);
    ctx.arc(x,y,r,0,2*Math.PI);
    ctx.fillStyle = gradient;
    ctx.fill();
}

draw_grd(50,50,50,"white","blue");
draw_grd(150,50,50,"green","red");
draw_grd(250,50,50,"black","pink");

And the result is:

enter image description here

JSFiddle link: http://jsfiddle.net/dsart/vogqzjnc/5/

What is it that I am missing? How to solve this?


Solution

  • Add ctx.beginPath(); before ctx.arc(x,y,r,0,2*Math.PI); and it should work fine. The problem here is that with your multiple function calls, you essentially chain the drawing paths together and your previous call has an impact on the next call.

    Here is the modified version: http://jsfiddle.net/ghbLzy72/69/

    Please note that I changed var to const. It's a good practice to use the new keywords (let and const) to initialize variables. You can leave this change out from your code if you prefer using var, but be aware of it's consequences and the impact it might have on your code (https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/).