Canvas createLinearGradient() Method

Definition and Usage

createLinearGradient() The method creates a linear gradient object.

Gradients can be used to fill rectangles, circles, lines, text, and more.

Tip:Please use the object as strokeStyle or fillStyle The value of the attribute.

Tip:Please use addColorStop() The method specifies different colors and where to locate the colors in the gradient object.

Examples

See also:

Define a gradient from black to white (from left to right) as the fill style for the rectangle:

Your browser does not support the HTML5 canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"black");
grd.addColorStop(1,"white");
ctx.fillStyle=grd;
ctx.fillRect(20,20,150,100);

Try it yourself

Syntax

context.createLinearGradient(x0,y0,x1,y1);

Parameter value

Parameter Description
x0 The x-coordinate of the start point of the gradient.
y0 The y-coordinate of the start point of the gradient.
x1 The x-coordinate of the end point of the gradient.
y1 The y-coordinate of the end point of the gradient.

More examples

Example 2

Define a gradient (from top to bottom) as the fill style for the rectangle:

Your browser does not support the canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0,170);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);

Try it yourself

Example 3

Define a gradient from black to red to white as the fill style for the rectangle:

Your browser does not support the canvas tag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,170,0);
my_gradient.addColorStop(0,"black");
my_gradient.addColorStop(0.5,"red");
my_gradient.addColorStop(1,"white");
ctx.fillStyle=my_gradient;
ctx.fillRect(20,20,150,100);

Try it yourself

Browser support

The numbers in the table indicate the first browser version that fully supports this attribute.

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
4.0 9.0 3.6 4.0 10.1

Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.