Will Hamic
Will Hamic

Reputation: 692

Radial Gradient in canvas doesn't fade 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 is a picture:

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

This for some reason fades to a black-like color rather than staying red. This leads it to act weird when two of these gradients of different colors are touching.

How can I make this react normally?

Upvotes: 3

Views: 1250

Answers (1)

user1693593
user1693593

Reputation:

Cause

The gradient defined is red-black and both the color and the alpha channel will be interpolated . At 50% it will be halfway between red and black, but also 50% visible which is why it is becoming black-ish.

Cure

To fix make sure both color stops are the same color which just the alpha channel changed. This will keep the color the same all the way:

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

Click the link below to see this 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>

Upvotes: 2

Related Questions