An example of linear and radial gradients on canvas tags

Written by Richard Heyes, on 17th April 2013

A guide explaining how to use gradients instead of named, hex, rgb() or hsl() colours. You can use linear or radial gradients with canvas and this page has examples of both types.

Introduction

Using colours with your canvas applications can be a simple affair - though when it comes to making gradients it gets a little more involved - but only a little. There are two types of gradient available - linear and radial. The former is a simple colour progression with colours slowly transitioning from the first to the second in a straight line. The second - radial gradients - are very similar but are circular in nature instead of a straight transition.

Linear gradients

An example of a linear gradient is:

[No canvas support]
var lgrad = context.createLinearGradient(0,0,600,0);
lgrad.addColorStop(0,'red');
lgrad.addColorStop(1,'white');

Here the gradient is defined as starting at [0,0] and going to [600,0] - ie a horizontal gradient. The coordinates are absolute coordinates - not width or height - so you could also look at it as:

var lgrad = context.createLinearGradient(x1, y1, x2, y2);

There are two colour stops defined - white and red. When you add colour stops the colour index can be from 0-1 and stipulates how far along the gradient it is. So here there are just two colours (but you can have more than two if you want) and the gradient transitions smoothly from the first (white) to the second (red).

Radial gradients

And an example of a radial gradient is:

[No canvas support]
var rgrad = context.createRadialGradient(70,50,0,70,50,100);
rgrad.addColorStop(0, '#fcc');
rgrad.addColorStop(1, 'red');

Here the gradient contains 6 values - the X/Y coordinates and radius of the start of the gradient and the X/Y coordinates of the end point with its radius. So you could also look at it like this:

var rgrad = context.createRadialGradient(x1, y1, r1, x2, y2, r2);

As shown above you can offset the X/Y coordinates from the center of a circle and achieve a spherical effect.