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
]
);
For example, if you want to create a linear gradient that starts at the beginning of the text (located 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
metrics
=
context
.
measureText
(
message
);
var
textWidth
=
metrics
.
width
;
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
form the gradations of the gradient fill. This is done with the addColorStop()
method, which requires two
arguments, offset
and color
:
gradient
.
addColorStop
([
offset
],[
color
]);
offset
This is the offset on the gradient line to start the color gradation. The entire gradient is represented by the numbers between 0.0 and 1.0. The offset will be a decimal that represents a percentage.
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() ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.