HTML and CSS Reference
In-Depth Information
Filling Shapes with Gradients
Therearetwobasicoptionsforcreatinggradientfillsonthecanvas:linearandradial.A
linear
gradient creates a horizontal, vertical, or diagonal fill pattern; the
radial
variety creates a fill
that “radiates” from a central point in a circular fashion. Let's look at some examples of each.
Linear gradients
Linear gradients come in three basic styles: horizontal, vertical, and diagonal. We control
where colors change in our gradient by setting
color stops
at points along the length of the
object we want to fill.
Linear horizontal gradients
Example 2-14
creates a simple horizontal gradient, as shown in
Figure 2-23
.
Example 2-14. A linear horizontal gradient
function
function
drawScreen
() {
// horizontal gradient values must remain 0
var
var
gr
=
context
.
createLinearGradient
(
0
,
0
,
100
,
0
);
// Add the color stops.
gr
.
addColorStop
(
0
,
'rgb(255,0,0)'
);
gr
.
addColorStop
(.
5
,
'rgb(0,255,0)'
);
gr
.
addColorStop
(
1
,
'rgb(255,0,0)'
);
// Use the gradient for the fillStyle.
context
.
fillStyle
=
gr
;
context
.
fillRect
(
0
,
0
,
100
,
100
);
}
Figure 2-23. A linear horizontal gradient
To create the horizontal gradient, we must first create a variable (
gr
) to reference the new
gradient. Here's how we set it: