Read my book

I wrote books about Webpack and React. Check them out!

Monday, August 2, 2010

HTML5 Canvas Gradients - Angular Gradient

In this part of the series I'm going to show you how to render angular gradient using HTML5 Canvas API. This is one of those gradients that's not covered by the API by default so it may come in handy. I will show a simplified version of the gradient and focus on the basics. It should be easy to extend on demand.
Angular Gradient

An angular gradient may be characterized by its location and colors. In addition colors may have an explicit stop value attached to them. In this case I will derive this way implicitly based on the ordering of the colors. Ie. if you provide red, green and blue colors to the gradient, you can expect the colors to be rendered in this particular order counter-clockwise around the location.

Here's my implementation:

You can find the files it depends on here.

In this case I ended up using inverse tangent (atan2) for figuring out the angle between current point and the gradient center. The basic idea is that the angle should represent a counter-clockwise rotation as if rotated from (1, 0). As the function returns negative, clockwise rotations for negative y, I ended up wrapping this particular case to counter-clockwise one.

I use the angle to figure out the colors to interpolate between and the interpolation factor. I decided to wrap the colors so that the "left" color of the first color should correspond to the last color.

Here's a sample render:


In this part of the series I showed you how to render a simple angular gradient. It's still missing nice features, like customizable stops, but it gets the job done adequately. This particular gradient can be combined with a radial gradient to render neat palettes. I have used this technique in my palette plugin (yet to be released).