CanvasRenderingContext2D: createLinearGradient() method
The CanvasRenderingContext2D.createLinearGradient()
method of the Canvas 2D API creates a gradient along the line connecting two given coordinates.

This method returns a linear CanvasGradient
. To be applied to a shape, the gradient must first be assigned to the fillStyle
or strokeStyle
properties.
Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates.
Syntax
createLinearGradient(x0, y0, x1, y1)
The createLinearGradient()
method is specified by four parameters defining the start and end points of the gradient line.
Parameters
-
x0
-
The x-axis coordinate of the start point.
-
y0
-
The y-axis coordinate of the start point.
-
x1
-
The x-axis coordinate of the end point.
-
y1
-
The y-axis coordinate of the end point.
Return value
A linear CanvasGradient
initialized with the specified line.
Exceptions
NotSupportedError
DOMException
-
Thrown when non-finite values are passed as parameters.
Examples
Filling a rectangle with a linear gradient
This example initializes a linear gradient using the createLinearGradient()
method. Three color stops between the gradient's start and end points are then created. Finally, the gradient is assigned to the canvas context, and is rendered to a filled rectangle.
HTML
<canvas id="canvas"></canvas>
JavaScript
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const gradient = ctx.createLinearGradient(20, 0, 220, 0);
gradient.addColorStop(0, "green");
gradient.addColorStop(0.5, "cyan");
gradient.addColorStop(1, "green");
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 100);
Result
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
createLinearGradient |
1 |
12 |
1.5 |
9 |
≤12.1 |
2 |
4.4 |
18 |
4 |
≤12.1 |
1 |
1.0 |
See also