Falcon80 Logo
Creating radial colour gradients on canvas

Radial gradient blends two or more colours in a circular/conical pattern and takes 5 arguments. Viz., x0,y0,r0,x1,y1,r1.

Where:


(x0,y0) is the centre coordinate of the first circle of the cone
r0 is the radius of the first circle
(x1,y1) is the centre coordinate of the second circle of the cone and
r1 is the radius of the second circle.

eg:

var gradient = ctx.createradialGradient(x0,y0,r0,x1,y1,r1)

The return object is now contained in the variable 'gradient'. The colour gradient that you create can have as many colours as you wish. With the fillcolorStop() method, you can specify a position between 0 and 1 where the transition to the next colour begins.

eg:
gradient.fillColorStop() = (0,"green");
gradient.fillColorStop() = (0.5,"rgb(0,255,0");
gradient.fillColorStop() = (1,"#FF0000");

Note that you can specify the colour any way you want viz., directly, as decimal values or as hexadecimal values. You can also add transparency to the colours either using rgba or using the globalAlpha attribute.

Once you define the colour gradient, you can assign the gradient object to the fillStyle() attribute. createLinearGradient() will also work on text.

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");

//Let's try the gradient on a rectangle

// Create a linear gradient from where the rectangle starts to where it ends horizontally
var fillColor = ctx.createRadialGradient(100,100,10,100,100,70);

// Specify the gradient colours
fillColor.addColorStop(0.2,"green");
fillColor.addColorStop(0.8,"red");

// Assign the gradient object to fillstyle
ctx.fillStyle= fillColor;

// Draw the rectangle
ctx.fillRect(50,50,100,100);

}
}
  </script>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>

Try Code