7

I'm playing around with createRadialGradient() on HTML5 canvas. It works like a charm, except when I'm trying to implement (semi-)transparency.

I made this jsFiddle to make things hopefully clearer: http://jsfiddle.net/rfLf6/1/.

function circle(x, y, r, c) {
    ctx.beginPath();
    var rad = ctx.createRadialGradient(x, y, 1, x, y, r);
    rad.addColorStop(0, c);
    rad.addColorStop(1, 'transparent');
    ctx.fillStyle = rad;
    ctx.arc(x, y, r, 0, Math.PI*2, false);
    ctx.fill();
}

ctx.fillRect(0, 0, 256, 256);

circle(128, 128, 200, 'red');
circle(64, 64, 30,    'green');

What is happening is a circle (radial gradient) is painted at (x, y) with radius r and the color stops are r and 'transparent'. However, the green circle is going from green to black, whilst it should go to transparent, i.e. the appropriate red colors of the background circle.

How does one implement transparent radial gradients on HTML5 canvas?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 1
    I'm not sure of the "proper method" of doing it, but this works: http://jsfiddle.net/thirtydot/BD3xA/ - but there's surely a nicer way. – thirtydot Apr 02 '11 at 21:14
  • @thirtydot: Thanks - that works just fine. You ought to post this as an answer. – pimvdb Apr 02 '11 at 21:16

1 Answers1

13

Well, since you asked:

I don't know much about using <canvas> with JavaScript, but I do know about CSS3 gradients, and the usual way to work with transparency is to use rgba colours.

To make the gradient "fade out" to transparent, you can add a transparent version of the same colour.

That's what I did here: http://jsfiddle.net/thirtydot/BD3xA/

thirtydot
  • 224,678
  • 48
  • 389
  • 349