Read my book

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

Wednesday, July 21, 2010

HTML5 Canvas Gradients - Linear Gradient

In this tutorial series I'm going to show you how to generate various gradients using the HTML5 canvas element. It provides two handy types by default: linear and radial (also known as circular). I will focus on these two types first and move onto more exotic ones, including angular, later on. Let's have a look at the most basic one, linear gradient, at first to get our feet wet.


Linear Gradient

It's probably a good idea to have a look at some code first and worry about the details later:



As usual first we have to set up a canvas. Once that's done we can access context. The context will allow us to actually draw something on the canvas. It provides some nice functionality beyond gradients. This functionality includes path API, transformations, pixel access etc. The full API has been documented by W3C.

Now that the context has been set up, we can set up gradient and render it. "createLinearGradient" defines the start and end points of the gradient. In this case I'm drawing the gradient diagonally from corner to corner. It would be easy to modify the gradient to be vertical or horizontal just by zeroing a suitable coordinate.

In this case I decided to stick to awesome yellow, green, black gradient and set up color stops accordingly. The first argument, offset determines how close to gradient bounds (start/end point) the color is. This second argument is given in standard CSS notation so you can use color names, hex notation or whatever you happen to find handy.

If you want to vary the alpha of the color, you can use the following notation 'rgba(0, 255, 0, 0.5)'. Note that the first three arguments of the color map to [0, 255] range while alpha is clamped to [0.0, 1.0]. By default alpha of each color is set to 1.0 so that colors are considered totally opaque by default.

Finally it's just a matter of rendering the gradient. In this case I decided to fill the whole canvas using it. If you load up the page you should end up with an image like this:

Conclusion

It didn't take that much code to come up with a simple linear gradient using HTML5 canvas. As we will see in the next post rendering a radial gradient is quite easy as well. After that things will get interesting, though. :)