/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: createLinearGradient()

[this page | pdf | back links]

The createLinearGradient() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element creates a linear gradient. The resulting object can be used as the value of the strokeStyle or fillStyle properties and hence to fill in rectangles, circles etc. You need to apply some addColorStop() methods to the gradient for it to be visible.

 

It has the following syntax with the following parameters.

 

context.createLinearGradient(xstart, ystart, xend, yend)

 

Parameter

Required / Optional

Description

xstart

Required

x-coordinate of gradient start point

xend

Required

y-coordinate of gradient start point

ystart

Required

x-coordinate of gradient end point

yend

Required

y-coordinate of gradient end point

 

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(15, 20, 80, 30);
g1.addColorStop(0, "blue");
g1.addColorStop(0.6, "yellow");
g1.addColorStop(0.8, "red");
c2.fillStyle = g1;
c2.fillRect(10, 10, 180, 80);

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

</body>
</html>

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


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


Desktop view | Switch to Mobile