THE INDIA LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

HTML canvas createLinearGradient() Method

HTML canvas Reference HTML Canvas Reference

Example

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

YourbrowserdoesnotsupporttheHTML5canvastag.

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 »

Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the createLinearGradient() method.

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


Definition and Usage

The createLinearGradient() method creates a linear gradient object.

The gradient can be used to fill rectangles, circles, lines, text, etc.

Tip: Use this object as the value to the strokeStyle or fillStyle properties.

Tip: Use the addColorStop() method to specify different colors, and where to position the colors in the gradient object.

JavaScript syntax: context.createLinearGradient(x0,y0,x1,y1);

Parameter Values

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

Examples

More Examples

Example

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

Yourbrowserdoesnotsupportthecanvastag.

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

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

Yourbrowserdoesnotsupportthecanvastag.

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 »

HTML canvas Reference HTML Canvas Reference