The addColorStop()
method
used together with createLinearGradient()
or createRadialGradient()
positions
the color in a gradient object.
We can use the addColorStop()
method
multiple times to change a gradient.
We need to create at least one color stop to have a visible gradient.
addColorStop() |
Yes | Yes | Yes | Yes | Yes |
gradient.addColorStop(stop,color>);
Parameter | Description |
---|---|
stop | A value between 0.0 and 1.0 that positions the color between start and end in a gradient |
color | A CSS color value displayed at the stop position |
The following code defines a gradient that goes from black to white. Then we use the gradient to fill a rectangle:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
<!-- ww w . j a v a 2 s .c om-->
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);
</script>
</body>
</html>
The code above is rendered as follows:
The following code defines a gradient with multiple addColorStop() methods:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
<!-- w ww . j ava 2 s . c o m-->
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "black");
grd.addColorStop("0.3", "magenta");
grd.addColorStop("0.5", "#EEE");
grd.addColorStop("0.6", "red");
grd.addColorStop("0.8", "yellow");
grd.addColorStop(1, "black");
ctx.fillStyle = grd;
ctx.fillRect(20, 20, 300, 200);
</script>
</body>
</html>
The code above is rendered as follows: