Gradients
Gradients can be used as fillStyle or strokeStyle to create smooth color transitions within shapes.
The canvas API includes methods to create linear and radial gradients:
| Method | Description |
|---|---|
createLinearGradient(x0, y0, x1, y1) |
Creates a linear gradient starting at (x0, y0) and ending at (x1, y1). |
createRadialGradient(x0, y0, r0, x1, y1, r1) |
Creates a radial gradient defined by two circles, where the first circle starts at (x0, y0) with radius r0 and the second circle ends at (x1, y1) with radius r1. |
Color Stops
Once a gradient object is created, use addColorStop() to define its color transitions:
| Method | Description |
|---|---|
addColorStop(offset, color) |
Adds a color stop at the specified offset (a value between 0.0 and 1.0) with the given color. |
Gradient Example
This example demonstrates how to create a linear gradient and a radial gradient and apply them to shapes:
The next lesson explains how to implement patterns for fills and strokes.