Falcon80 Logo
Creating linear colour gradients on canvas

We already saw how to fill a closed figure with a specific colour. But what if we want a gradient? the createLinearGradient() and createRadialGradient() methods serve adequately for the purpose. The createLinearGradient method creates a gradient along a straight line specified by two point (x0,y0) and (x1,y1). The method returns an object.

eg:

var gradient = ctx.createLinearGradient(x0,y0,x1,y1)

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.

Once you define the colour gradient, you can assign the gradient object to the fillStyle() attribute or even the strokeStyle() 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.createLinearGradient(50,50, 150,50);

// 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);

//Now, let's try the same thing with text

var fillColorText = ctx.createLinearGradient(300,60, 400,60);
fillColorText.addColorStop(0,"green");
fillColorText.addColorStop(1,"rgba(255,0,0,0.5)");
ctx.fillStyle= fillColorText;

ctx.font="40px verdana";
ctx.textBaseline="top";
ctx.fillText("Believe", 300,50)

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