HTML and CSS Reference
In-Depth Information
This function has two parameters: the position of the color in the gradient (this should be a value between 0 and 1)
and the color.
After you have added all of your color stops, you apply your gradient to an object on the canvas by setting the
fillStyle property to your gradient variable. The following example code shows how to create a simple gradient
and apply it to a rectangle.
var linGrad = ctx.createLinearGradient(0,0,0,160);
linGrad.addColorStop(0, “#009A00");
linGrad.addColorStop(1, “#085A00");
ctx.rect(0,0,200, 160)
ctx.fillStyle = linGrad;
ctx.fill();
This code would draw a rectangle on the canvas and fill it with the gradient shown in Figure 14-10.
Figure 14-10 A simple canvas gradient.
The rect() function used in this example is very similar to the fillRect() function that you encountered earlier
in this chapter. The difference is that the rect() function will draw a rectangle but will not initiate a fill.
Now that you understand how Canvas gradients work, let's add a gradient to the circle that you created in the previ-
ous section.
The code in this exercise can be found in folder 8.
Here are the steps:
Search WWH ::




Custom Search