HTML and CSS Reference
The code in the previous listing uses the 2D context object to
generate a linear gradient object to which you can then apply
colour stops. The arguments are the starting point of the gra-
dient, x1 and y1, and the end point of the gradient, x2 and y2.
In this example, I'm telling the gradient to start in the top left
and fi nish at the bottom of the canvas on the left. This creates
a gradient that runs vertically ( Figure 5.6 ).
Radial gradients are very similar, except the createRadialGradient
takes the radius after each coordinate:
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d'),
gradient = ctx.createRadialGradient(canvas.width/2,
canvas.width/2, canvas.height/2, 150);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.width);
The only difference is what kind of gradient you've created. In
this example, I've moved the fi rst point of the gradient to start in
the centre of the canvas starting with a radius of zero. The gra-
dient uses a radius of 150 radians, but notice that it also starts in
the same place: canvas.width/2, canvas.height/2 . This is so my
example creates a nice smooth circular gradient ( Figure 5.7 ).
FIGURE 5.6 A vertical
gradient on a canvas element.
FIGURE 5.7 A radial gradient
that starts and ends from the
same point, but the ending
radius is much greater causing
a smooth circular gradient.
Getting from degrees to radians
All the radius and arc methods use radians, so if you're used to work-
ing with degrees, you'll need to convert them to radians. Here's the
var radians = degrees * Math.PI / 180;
It's also common to pass 360 degrees to the drawing methods, which
is simply Math.PI * 2 , and equally 180 degrees is Math.PI .
Patterns are even easier to use. You need a source, then you
can drop the source element into the createPattern method
and use the result as the fillStyle . The only caveat is that the
element must have fi nished loading, in the case of images and
videos, to capture the source properly.