CanvasRenderingContext2D: createLinearGradient() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheCanvasRenderingContext2D.createLinearGradient()method of the Canvas 2D API creates a gradient along the line connecting two givencoordinates.

This method returns a linearCanvasGradient. To be applied to a shape,the gradient must first be assigned to thefillStyle orstrokeStyle properties.
Note:Gradient coordinates are global, i.e., relative to the currentcoordinate space. When applied to a shape, the coordinates are NOT relative to theshape's coordinates.
In this article
Syntax
createLinearGradient(x0, y0, x1, y1)ThecreateLinearGradient() method is specified by four parameters definingthe start and end points of the gradient line.
Parameters
Return value
A linearCanvasGradient initialized with the specified line.
Exceptions
NotSupportedErrorDOMExceptionThrown when non-finite values are passed as parameters.
Examples
>Filling a rectangle with a linear gradient
This example initializes a linear gradient using thecreateLinearGradient() method. Three color stops between the gradient'sstart and end points are then created. Finally, the gradient is assigned to the canvascontext, and is rendered to a filled rectangle.
HTML
<canvas></canvas>JavaScript
const canvas = document.getElementById("canvas");const ctx = canvas.getContext("2d");// Create a linear gradient// The start gradient point is at x=20, y=0// The end gradient point is at x=220, y=0const gradient = ctx.createLinearGradient(20, 0, 220, 0);// Add three color stopsgradient.addColorStop(0, "green");gradient.addColorStop(0.5, "cyan");gradient.addColorStop(1, "green");// Set the fill style and draw a rectanglectx.fillStyle = gradient;ctx.fillRect(20, 20, 200, 100);Result
Specifications
| Specification |
|---|
| HTML> # dom-context-2d-createlineargradient-dev> |
Browser compatibility
See also
- The interface defining this method:
CanvasRenderingContext2D CanvasRenderingContext2D.createRadialGradient()CanvasRenderingContext2D.createConicGradient()