HTML and CSS Reference
n Note In CSS, an RGB value can be obtained using the functional notation formats rgb() and rgba() . rgb()
uses red, green, and blue components to form a color. rgba() uses an additional component—alpha—that controls
the color's transparency.
A gradient specifies a range of colors that are used to fill a shape. The gradient effect applies color ranges
continuously between the start and end positions, thus producing a smooth color transition. A gradient
can be of two types : linear or radial.
A linear gradient is defined by two points and a color at each of those points. The colors along the line
joining these two points vary based on a color stop.
A radial gradient is defined by two circles, each of which has a color. The gradient radiates out from
the starting circle to the ending circle, and colors are calculated based on color stops.
To fill a shape with a linear or radial gradient, you first need to create a corresponding gradient object
and then define the required color stops. Finally, you fill a shape with the fillStyle property set to the
gradient object just created.
Listing 4-16 shows how you can fill a rectangle with a linear gradient.
Listing 4-16. Drawing a Linear Gradient
var canvas = $("#MyCanvas").get(0);
var context = canvas.getContext("2d");
var linearGradient = context.createLinearGradient(0, 100, 200, 100);
context.fillStyle = linearGradient;
context.fillRect(0, 0, 200, 200);
This code creates a linear gradient object using the drawing context's createLinearGradient()
method. The first two parameters of createLinearGradient() represent the x and y coordinates of the
gradient's start point. Similarly, the last two parameters represent the x and y coordinates of the end point.
The gradient is drawn from the start point to the end point.
The code adds three further color stops. The color-stop offset values range from 0 to 1 (from the start
of the gradient to the end). The drawing context's fillStyle property is set to the linear gradient object, and
then fillRect() is called. Figure 4-18 shows the resulting gradient-filled rectangle.