HTML 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 property.
Tip:Please use addColorStop() The method specifies different colors and where to locate the colors in the gradient object.
Example
See also:
Define a gradient from black to white (from left to right) as the fill style for a rectangle:
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);
Syntax
context.createLinearGradient(x0,y0,x1,y1);
Parameter value
Parameter | Description |
---|---|
x0 | The x-coordinate of the gradient start point |
y0 | The y-coordinate of the gradient start point |
x1 | The x-coordinate of the gradient endpoint |
y1 | The y-coordinate of the gradient endpoint |
More examples
Example 2
Define a gradient (from top to bottom) as the fill style for a rectangle:
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);
Example 3
Define a gradient from black to red and then to white as the fill style for a rectangle:
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);
Browser Support
The numbers in the table indicate the first browser version that fully supports this property.
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.