An example of linear and radial gradientsShare RGraph:
Posted on 17th April 2013
A guide explaining how to use gadients instead of named, hex, rgb() or hsl() colors. You can use linear or radial gradients with canvas and this page has examples of both types.
Using colors 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 color progression with colors slowly transistioning 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.
An example of a linear gradient is:
var lgrad = context.createLinearGradient(0,0,600,0); lgrad.addColorStop(0,'red'); lgrad.addColorStop(1,'white');
Here the gradient 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 color stops defined - white and red. When you add color stops the color "index" can be from 0-1 and stipulates how far along the gradient it is. So here there are just two colors (but you can have more than two if you wish) and the gradient transitions smoothly from the first (white) to the second (red).
And an example of a radial gradient is:
var rgrad = context.createRadialGradient(70,50,0,70,50,100); rgrad.addColorStop(0, '#fcc'); rgrad.addColorStop(1, 'red');
Here the gradient conatins 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.