HTML and CSS Reference
In-Depth Information
Figure 4-5. Linear gradient fills
A radial gradient fill starts in the center of the space you define and radiates outward in all directions,
creating a circle. The first color you specify is at the center of the circle, and the final color is the edge. The
method, context.createRadialGradient(x0, y0, r0, x1, y1, r1) , takes arguments representing
two circles each specified by a coordinate and a radius. Figure 4-6 shows an example of a radial fill.
Figure 4-6. Radial gradient fill
Setting gradient color stops
To see a gradient fill, you need at least two different color stops, or color positions, on the gradient. If that's
all you specify, the fill blends from the first to the second. If you add more colors, the fill blends smoothly
from the first, to the second, to the third, and so on, until it arrives at the last one.
You must also specify the position of each color in the fill by assigning it a decimal number from 0 to 1,
where 0 is the start of the fill and 1 is the end. These numbers, one for each color, are called the ratio of
the fill. For example, if you want a two-color fill, specify 0 and 1 as the ratios. To make an even blend of
three colors, use 0, 0.5, and 1 as ratios—this puts the second color exactly in the middle of the other two.
If you use 0, 0.1, 1 as ratios, the first color almost immediately blends into the second, and then very
slowly blends into the third. Keep in mind that these are not pixel values, but fractions of 1.
With a ratio and color, add a color stop using the gradient's method Gradient.addColorStop(ratio, color) :
var gradient = context.createLinearGradient(0, 0, 100, 100);
gradient.addColorStop(0, "#ffffff");
gradient.addColorStop(1, "#ff0000");
This creates a linear gradient from point (0, 0) to point (100, 100). It then defines two color stops using a
start ratio of 0 and end ratio of 1. This gradient color starts as white and blends into red at the end.
The next step is to assign the gradient to context.fillStyle and draw a shape with it:
context.fillStyle = gradient;
context.fillRect(0, 0, 100, 100);
 
Search WWH ::




Custom Search