/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: addColorStop()

[this page | pdf | back links]

The addColorStop() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element specifies colours and stop positions for a gradient object, created by createLinearGradient() or createRadialGradient(). You need to include at least one colour stop for a gradient to be visible.

 

It has the following syntax with the following parameters.

 

gradient.addColorStop(stop, color)

 

Parameter

Required / Optional

Description

type

Required

A value between 0.0 and 1.0 identifying the position of the stop used in a gradient

color

Optional

Specified CSS colour to display at the position of the stop

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span>

<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "100");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");

var g1 = c2.createLinearGradient(0, 0, 80, 30);
g1.addColorStop(0, "blue");
g1.addColorStop(0.6, "yellow");
g1.addColorStop(0.8, "red");
c2.fillStyle = g1;
c2.fillRect(10, 15, 80, 70);

document.getElementById("element").appendChild(x2);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodCanvas2dAddColorStop() {
  var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.addColorStop;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile