HTML canvas addColorStop()Method
Example
Define a gradient from black to white as the fill style of the 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);
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 9, Firefox, Opera, Chrome, and Safari support the addColorStop() method.
Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.
Definition and Usage
The addColorStop() method specifies the color and position in a gradient object.
The addColorStop() method andcreateLinearGradient()orcreateRadialGradient()are used together.
Note:You can call the addColorStop() method multiple times to change the gradient. If you do not use this method on the gradient object, the gradient will not be visible. To obtain a visible gradient, you need to create at least one color stop.
| JavaScript syntax: | gradient.addColorStop(stop,color); |
|---|
Parameter Values
| Parameter | Description |
|---|---|
| stop | A value between 0.0 and 1.0, representing the position between the start and end of the gradient. |
| color | InstopDisplayed at the positionCSS color value。 |

More Examples
Example
Define a gradient with multiple addColorStop() methods:
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("0.3","magenta");
grd.addColorStop("0.5","blue");
grd.addColorStop("0.6","green");
grd.addColorStop("0.8","yellow");
grd.addColorStop(1,"red");
ctx.fillStyle=grd;
ctx.fillRect(20,20,150,100);
var ctx=c.getContext("2d");
var grd=ctx.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"black");
grd.addColorStop("0.3","magenta");
grd.addColorStop("0.5","blue");
grd.addColorStop("0.6","green");
grd.addColorStop("0.8","yellow");
grd.addColorStop(1,"red");
ctx.fillStyle=grd;
ctx.fillRect(20,20,150,100);
Try it Yourself »
Other Extensions
Canvas Object