HTML and CSS Reference
In-Depth Information
Linear Gradients and Text
To create a linear gradient, make a call to the context's
createLinearGradient()
method
to create a
Gradient
object. The
createLinearGradient()
method accepts four parameters
that all define the line of the linear gradient. The
x0
and
y0
parameters are the starting point
of the line, and
x1
and
y1
represent the ending point of the line:
var
gradient
=
context
.
createLinearGradient
(
[
x0
]
,
[
y0
]
,
[
x1
]
,
[
y1
]
);
Forexample,ifyouwanttocreatealineargradientthatstartsatthebeginningofthetext(loc-
ated at 100,100) and has an endpoint that is the width of your text as displayed on the canvas,
you might write the following code:
var
var
var
metrics
=
context
.
measureText
(
message
);
var
var
textWidth
=
metrics
.
width
;
var
var
gradient
=
context
.
createLinearGradient
(
100
,
100
,
textWidth
,
100
);
After you have created the line that represents the gradient, you need to add colors that will
formthegradationsofthegradientfill.Thisisdonewiththe
addColorStop()
method,which
requires two arguments,
offset
and
color
:
gradient
.
addColorStop
([
offset
],[
color
]);
offset
Thisistheoffsetonthegradientlinetostartthecolorgradation.Theentiregradientisrep-
resented by the numbers between 0.0 and 1.0. The offset will be a decimal that represents
a percentage.
color
color
A valid CSS color in the format “#RRGGBB”.
So, if you want black to be the first color in the gradient and red to be the second color that
starts halfway down the gradient line, you would create two calls to
addColorStop()
:
gradient
.
addColorStop
(
0
,
"#000000"
);
gradient
.
addColorStop
(.
5
,
"#FF0000"
);
NOTE
If you fail to add colors with
addColorStop()
, the text will be rendered invisible.
The results are shown in
Figure 3-9
.