Colors and Transparency
By default, all shapes drawn on the canvas are solid black. You can use the fillStyle, strokeStyle, and globalAlpha properties to customize the appearance of your drawings.
Colors
To set the color for shapes or strokes, use the fillStyle and strokeStyle properties:
| Property | Description |
|---|---|
fillStyle |
Sets the color (or gradient, or pattern) used for filling shapes. |
strokeStyle |
Sets the color (or gradient, or pattern) used for shape outlines. |
These properties accept any valid CSS color value, including:
- Named Colors (e.g.,
"blue","orange") - Hexadecimal values (e.g.,
"#0070C0","#FF8C00") - RGB or RGBA strings (e.g.,
"rgb(0, 112, 192)","rgba(255, 140, 0, 0.5)") - HSL or HSLA strings (e.g.,
"hsl(200, 100%, 38%)")
Transparency
There are two ways to draw transparent shapes on the canvas:
- Specify a transparent color using
rgb()orhsl()(or their explicit alpha versionsrgba()orhsla()). - Set the
globalAlphaproperty to a value between0.0(fully transparent) and1.0(fully opaque). Any shapes drawn after setting this property will use that transparency level.
Color and Transparency Example
This example demonstrates how to apply various colors and transparency levels to rectangles:
The next lesson explains how to implement gradients.