Latest web development tutorials

HTML canvas createLinearGradient () method

HTML canvas Reference Manual HTML canvas Reference Manual

Examples

Definition from black to white gradient (left to right), a rectangle fill style:

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"

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

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

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


Definition and Usage

createLinearGradient () method creates a linear gradient object.

Gradient can be used to fill rectangles, circles, lines, text, and so on.

Tip: Use this object as strokeStyle or fillStyle value of the property.

Tip: Use addColorStop () method specifies a different color, as well as where to locate the color gradient object.

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

Parameter Value

参数 描述
x0 渐变开始点的 x 坐标
y0 渐变开始点的 y 坐标
x1 渐变结束点的 x 坐标
y1 渐变结束点的 y 坐标


Examples

More examples

Examples

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

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"

Examples

Define a from black to red and then to white gradient, a rectangle fill style:

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"


HTML canvas Reference Manual HTML canvas Reference Manual