HTML and CSS Reference
In-Depth Information
Text with Gradients and Patterns
We've already explored the
fillColor
and
strokeColor
properties of the Canvas context
by setting those value to CSS-compliant colors. However, those very same properties
can be set to refer to a few other objects defined in the Canvas API to create some
stunning text effects. The objects are:
Linear gradient
A linear color gradient with two or more colors
Radial gradient
A circular color gradient with two or more colors
Image pattern
An
Image
object used as a fill pattern
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 param-
eters 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 then red to be the second
color that starts halfway down the gradient line, you would create two calls to
add
ColorStop()
: