/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object method: createRadialGradient()

[this page | pdf | back links]

The createRadialGradient() method of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element creates a radial (i.e. circular) 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.createRadialGradient(xstart, ystart, rstart, xend, yend, rend)

 

Parameter

Required / Optional

Description

xstart

Required

x-coordinate of centre of starting circle of gradient

xend

Required

y-coordinate of centre of starting circle of gradient

rstart

Required

Radius of starting circle

ystart

Required

x-coordinate of centre of ending circle of gradient

yend

Required

y-coordinate of centre of ending circle of gradient

rend

Required

Radius of ending circle

 

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.createRadialGradient(40, 40, 20, 50, 45, 50);
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 isSupportedJavaScriptMethodCanvas2dCreateRadialGradient() {
  var x = document.createElement("CANVAS"); var c = x.getContext("2d"); return !!c.createRadialGradient;
}


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


Desktop view | Switch to Mobile