Radial gradient in canvas does not fade out properly

I am trying to make a radial gradient with a Javascipt / HTML canvas. The problem is that the gradients don't overlap properly, as if the alpha channel isn't working.

This is the code I am using:

var gradient1 = ctx.createRadialGradient(300, 300, 300, 300, 300, 0);
gradient1.addColorStop(0,"rgba(0, 0, 0, 0)");
gradient1.addColorStop(1,"#FF0000");
ctx.fillStyle = gradient1;
ctx.fillRect(x1, y1, 600, 600);
ctx.fillRect(x1, y1, 600, 600);

      

Here's a picture:

http://i.imgur.com/tV5r48h.png

It fades out to black for some reason instead of staying red. This makes it act oddly when two of these gradients of different colors touch each other.

How can I get this to react normally?

+3


source to share


1 answer


Cause

The defined gradient is red to black and the color and alpha will be interpolated. At 50% it will be halfway between red and black, but also 50% visible, so it turns black.

Treatment

To fix this, make sure both color stops are the same color that only the alpha channel changed. This will maintain color in the same way:



gradient1.addColorStop(0, "rgba(255, 0, 0, 0)"); // red, but transparent
gradient1.addColorStop(0, "#f00");               // red, solid

      

Click the link below to see it in action:

var ctx = document.querySelector("canvas").getContext("2d");

var gradient1 = ctx.createRadialGradient(300, 300, 300, 300, 300, 0);
gradient1.addColorStop(0,"rgba(255, 0, 0, 0)");
gradient1.addColorStop(1,"#FF0000");
ctx.fillStyle = gradient1;
ctx.fillRect(0, 0, 600, 600);
ctx.fillRect(0, 0, 600, 600);
      

<canvas width=600 height=600></canvas>
      

Run codeHide result


+3


source







All Articles