Canvas Linear Gradients

What You’ll Learn
Canvas linear gradients let you fill or stroke shapes with smooth color transitions. You define a gradient axis using two points, then place colors along that axis with stops.
This page teaches createLinearGradient(), addColorStop(), and how to apply gradients to fills and strokes.
⚡ Quick Reference
const g = ctx.createLinearGradient(x0, y0, x1, y1);
g.addColorStop(0, 'red');
g.addColorStop(1, 'blue');
ctx.fillStyle = g;
ctx.fillRect(20, 20, 150, 100);x0, y0Where stop 0 begins
x1, y1Where stop 1 ends
0 → 1Offsets are fractions along the axis
fillStyle / strokeStyleUse for fill or outline
👀 Live Preview — Direction & Stops
Adjust the gradient direction and stop positions/colors. The preview renders a rounded rectangle and a gradient stroke line.
Tip: Add more color stops for sharper transitions or multi-color gradients. Stops must be between 0 and 1.
Basic Gradient Fill
This mirrors the legacy example: a horizontal gradient from red to blue used to fill a rectangle.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 150, 100);Gradient Stroke (Neon-ish Outline)
You can apply gradients to strokes as well. This is great for outlines, borders, and glow effects.
const g = ctx.createLinearGradient(50, 0, 350, 0);
g.addColorStop(0, '#22c55e');
g.addColorStop(0.5, '#60a5fa');
g.addColorStop(1, '#f97316');
ctx.lineWidth = 10;
ctx.lineCap = 'round';
ctx.strokeStyle = g;
ctx.beginPath();
ctx.moveTo(60, 80);
ctx.lineTo(360, 80);
ctx.stroke();💡 Best Practices
Do
- Choose axis points that match your shape’s size for predictable results
- Add 3+ stops for richer gradients (not just two colors)
- Reuse the same gradient for fill and stroke for consistent styling
- Use alpha (rgba/hsla) stops for soft fades
- Keep stop offsets within 0..1 to avoid errors
Don’t
- Use identical start/end points (you’ll get a solid color)
- Forget to assign the gradient to
fillStyle/strokeStyle - Assume gradients are tied to a shape (they are defined in canvas coordinates)
- Rely on only named colors (hex/rgba gives more control)
- Over-create gradients in tight animation loops without caching
❓ Frequently Asked Questions
createLinearGradient(x0, y0, x1, y1). Add stops using addColorStop(), then assign it to fillStyle or strokeStyle.strokeStyle and then call stroke() on a path.Next: Manipulating Images
Learn how to draw images and manipulate pixels using the canvas API.
4 people found this page helpful
