Canvas Radial Gradients

What You’ll Learn
Radial gradients are great for glows, lighting, and depth. Unlike linear gradients, you define the gradient using two circles: an inner circle and an outer circle.
By offsetting the circles, you can create highlights and spotlights that feel more natural.
⚡ Quick Reference
const g = ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
g.addColorStop(0, 'red');
g.addColorStop(1, 'green');
ctx.fillStyle = g;
ctx.fillRect(0, 0, canvas.width, canvas.height);(x0, y0, r0)Often r0 = 0 for a glow center
(x1, y1, r1)Controls how far the gradient spreads
0 → 1Offsets are fractions of the gradient
fillStyle / strokeStyleFill shapes or stroke paths
👀 Live Preview — Center, Focus & Radii
Move the inner/outer circle centers and change radii. Try offsetting the inner circle to create a highlight.
Tip: For a glow, use r0 = 0 and an outer color with alpha (like rgba(..., 0)). For highlights, offset (x0,y0) from (x1,y1).
Basic Radial Gradient Fill
This mirrors the legacy example: a center-out gradient used to fill a rectangle.
const gradient = ctx.createRadialGradient(200, 200, 0, 200, 200, 200);
gradient.addColorStop(0, 'red');
gradient.addColorStop(0.5, 'yellow');
gradient.addColorStop(1, 'green');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 400, 400);Glow Effect (Soft Edge)
Use alpha at the outer stop to fade to transparent. This is ideal for glowing UI elements.
const cx = 220, cy = 140;
const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, 120);
g.addColorStop(0, 'rgba(96, 165, 250, 0.95)');
g.addColorStop(1, 'rgba(96, 165, 250, 0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, canvas.width, canvas.height);💡 Best Practices
Do
- Use
r0 = 0for glow centers - Use alpha (rgba/hsla) stops for smooth fades
- Offset inner and outer centers for realistic highlights
- Add 3+ stops to sculpt the falloff curve
- Cache gradients if you reuse them many times
Don’t
- Use identical radii and expect a gradient (r0=r1 is often flat)
- Forget to set
fillStyle/strokeStylebefore drawing - Assume the gradient is tied to a shape (it’s in canvas coordinates)
- Overuse very large gradients in tight animation loops without profiling
- Rely on only two stops for complex lighting
❓ Frequently Asked Questions
fillStyle or strokeStyle.r0 is the inner radius; r1 is the outer radius. A common glow is r0=0.r0 ~= r1), add more than one stop, and apply the gradient before drawing.Next: Canvas Rotate
Rotate the canvas coordinate system to draw rotated images and shapes.
4 people found this page helpful
