SyntaxStudy
Sign Up
HTML Intermediate 5 min read

Canvas Gradients

Canvas Gradients

Create gradients with createLinearGradient() or createRadialGradient(), add color stops, then assign the gradient as a fillStyle or strokeStyle.

Example
const ctx = canvas.getContext("2d");

// Linear gradient
const linear = ctx.createLinearGradient(0, 0, 400, 0);
linear.addColorStop(0, "#007bff");
linear.addColorStop(0.5, "#6f42c1");
linear.addColorStop(1, "#e83e8c");
ctx.fillStyle = linear;
ctx.fillRect(0, 0, 400, 100);

// Radial gradient
const radial = ctx.createRadialGradient(200, 250, 10, 200, 250, 100);
radial.addColorStop(0, "white");
radial.addColorStop(1, "#007bff");
ctx.fillStyle = radial;
ctx.arc(200, 250, 100, 0, Math.PI * 2);
ctx.fill();
Pro Tip

Position gradients in canvas coordinate space to match the area you are filling — not relative to the shape.