Canvas addColorStop() Method

Definition and usage

addColorStop() method specifies the color and position in the gradient object.

The addColorStop() method with createLinearGradient() or createRadialGradient() 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 create a visible gradient, you need to create at least one color stop.

Instance

Example 1

Define a gradient from black to white 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

Tip:More examples are provided at the bottom of the page.

Syntax

gradient.addColorStop(stop,color);

Parameter value

Parameter Description
stop A value between 0.0 and 1.0, indicating the position between the start and end of the gradient.
color CSS color value displayed at the end position.

More examples

Example 2

Define the gradient by using multiple addColorStop() methods:

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("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

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.