Fill and Stroke Styles
You'll learn how to apply colors, gradients, and patterns to shapes on the Canvas API using fillStyle and strokeStyle properties.
When you draw shapes on a canvas, you have two main visual properties to control: the fill (interior color) and the stroke (outline color). Think of it like coloring a drawing—fillStyle is the crayon you use to color inside the lines, while strokeStyle is the marker you use to trace the outline.
Basic Color Application
Both fillStyle and strokeStyle accept color values in familiar CSS formats—color names, hex codes, RGB, or RGBA:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Solid color fill
ctx.fillStyle = 'steelblue';
ctx.fillRect(10, 10, 100, 100);
// Different stroke color
ctx.strokeStyle = '#FF6347'; // Tomato red
ctx.lineWidth = 5;
ctx.strokeRect(130, 10, 100, 100);
// RGBA for transparency
ctx.fillStyle = 'rgba(0, 128, 0, 0.5)'; // Semi-transparent green
ctx.fillRect(250, 10, 100, 100);
Gradients
For more sophisticated visuals, you can create linear or radial gradients:
// Linear gradient
const linearGrad = ctx.createLinearGradient(10, 140, 110, 140);
linearGrad.addColorStop(0, 'purple');
linearGrad.addColorStop(1, 'orange');
ctx.fillStyle = linearGrad;
ctx.fillRect(10, 140, 100, 100);
// Radial gradient
const radialGrad = ctx.createRadialGradient(180, 190, 10, 180, 190, 50);
radialGrad.addColorStop(0, 'white');
radialGrad.addColorStop(1, 'navy');
ctx.fillStyle = radialGrad;
ctx.fillRect(130, 140, 100, 100);
Patterns
You can also fill with repeating patterns from images or other canvases (though this requires image loading outside the basic scope).
Key Takeaway: Use fillStyle to control interior colors and strokeStyle for outlines—both accept solid colors, gradients, and patterns, giving you complete control over how your canvas shapes appear visually.