Set the Context's FillStyle Property to a Gradient
Besides colors, we can also assign a gradient to the
context.fillStyle
property using either the
context.createLinearGradient()
method or the
context.createRadialGradient()
method.
In this example, we create a horizontal linear gradient and assign it to the variable
gradient
using:
var gradient = context.createLinearGradient(50, 0, 350, 0);
This creates a linear gradient between (50, 0) and (350, 0). If we draw a straight line
between (50, 0) and (350, 0), we get a horizontal line. To create a vertical linear gradient,
use two points that form a vertical line. We can also create linear gradients at an angle.
We then add two color stops. The first color stop sets the color at position 0 (50, 0) to
MediumPurple. The second color stop sets the color at position 1 (350, 0) to Black. Any
points between (50, 0) and (350, 0) will be filled with a mixture of MediumPurple and Black.
gradient.addColorStop(0, 'MediumPurple');
gradient.addColorStop(1, 'Black');
We can define a linear gradient with more than two color stops by adding additional color
stops at positions between 0-1.
Finally, we assign
gradient
to
context.fillStyle
and use the
context.fillRect()
method to draw three filled rectangles.
context.fillStyle = gradient;
context.fillRect(20, 20, 300, 80);
context.fillRect(200, 120, 200, 80);
context.fillRect(80, 220, 200, 80);
It is important to note that the gradient is defined for the context and within the
context's coordinate system. A rectangle positioned to the right of (350, 0) and filled
with the gradient will be solid black.
To learn more about the coordinate system, variables, and linear gradients, visit the
Coordinates,
Variables,
and
createLinearGradient()
lessons.
Quick Reference:
Coordinates
Variables