On an <canvas>, createLinearGradient(x0, y0, x1, y1) builds a color blend along a straight line. It returns a CanvasGradient. Add stops with addColorStop(), then assign it to fillStyle or strokeStyle before you draw.
Gradient coordinates are global (canvas space), not local to the shape. Match the gradient line to where you paint — a common beginner pitfall. For circular blends, see radial gradients.
Baseline · Widely available.
createLinearGradient and addColorStop are stable Canvas 2D features across modern browsers since about July 2015.
Invalid stops throw.
Offset outside 0–1 → IndexSizeError. Unparseable color → SyntaxError. Keep offsets in range and use valid CSS colors.
Syntax
Syntax
gradient.js
const g = ctx.createLinearGradient(x0, y0, x1, y1);
g.addColorStop(0, "colorA");
g.addColorStop(1, "colorB");
ctx.fillStyle = g;
ctx.fillRect(x, y, w, h);
The same gradient object can also be assigned to strokeStyle for outlined shapes or text.
Reference
Key Methods
Core linear-gradient tools:
Method / param
Description
Try it
createLinearGradient(x0, y0, x1, y1)
Create a gradient along the line from start to end
createLinearGradient and addColorStop are part of the Canvas 2D API in every modern browser.
✓ Baseline · Widely available
Linear gradients
Widely available since about July 2015. Chrome, Firefox, Safari, Edge, and Opera support linear CanvasGradient fills and strokes. Internet Explorer 9+ also supports them.
98%Global support (approx.)
Google ChromeAll modern
Full support
Mozilla FirefoxAll modern
Full support
Apple SafariAll modern
Full support
Microsoft EdgeAll modern
Full support
OperaAll modern
Full support
Samsung InternetAll modern
Full support
Internet Explorer9+
Supported
createLinearGradientWidely supported
Bottom line: Safe for production fills, strokes, and soft fades on Canvas 2D everywhere modern browsers run.
Gradients are a Canvas API concern. The <canvas> element still uses typical user-agent CSS:
default.css
canvas {
display: inline;
}
Set bitmap size with HTML width/height. CSS-only sizing scales the bitmap and can soften gradient edges.
Frequently Asked Questions
Call createLinearGradient(x0, y0, x1, y1), add color stops with addColorStop(offset, color), assign the gradient to fillStyle or strokeStyle, then draw.
A number from 0 to 1. 0 is the gradient start point; 1 is the end point. Values outside 0–1 throw IndexSizeError.
Gradient coordinates are global (canvas space), not relative to the shape. Align the gradient line with where you draw, or transform the context first.
Yes. Set strokeStyle to the CanvasGradient, then stroke() a path or use strokeRect / strokeText.
At least one works, but two (0 and 1) is the usual minimum for a blend. Add more stops for multi-color ramps.
Ideas are similar, but canvas gradients are CanvasGradient objects applied through fillStyle/strokeStyle in the 2D API, not CSS background images.