Read my book

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

Thursday, July 22, 2010

HTML5 Canvas Gradients - Radial Gradient

In this part of the gradient series I'm going to show you how to render a radial gradient using HTML5 canvas. I will come up with a simple gradient that follows your mouse cursor as you move it around the canvas.

Radial Gradient

As usual I will start out with some code and explain it a bit later:

As before I start out by setting up canvas and context. A radial gradient is defined two triplets (x, y, radius). The first one defines the center while the latter one defines the outer bounds.

Color stops are defined just like for the linear gradient before. In this case I decided to store the stop items in an associative array as this provides nice and easy way of modifying them later on.

In addition I set up a move function that's triggered as the user moves the mouse over the canvas. The idea is that the location of the gradient center is varied based on the location of the cursor.

I'm not entirely sure if the code figuring out the mouse coordinates on the canvas is entirely correct but it does seem to do the trick in this case well enough.

Note the way I check for the existence of x and y parameters in the draw function. A naive check (ie. var gradientCenterX = x? x: halfWidth;) is bound to fail in the case x is zero. It's better to check if it has been defined.

If you decide to play around with the example, note how ugly the gradient becomes if the user moves the mouse near corners of the canvas. It's possible to remedy this issue by projecting the mouse coordinates to the circle (find intersection). You might also want to vary the value of the center radius to alter the size of the pupil. Playing around with the colors might be interesting as well.

Here's an example of what the gradient looks like in practice:


In this part of the series I showed you how to render a simple radial gradient and add some interaction to it. Next I will delve into something quite different, pixel-wise operations and a simple variant of linear gradient.