Gradients
Canvas can both fill and stroke shapes using linear or radial gradients.
Linear gradients
A linear gradient fills an area by blending the colors provided as stops. It can have any number of stops, but must have at least two. It is called a linear gradient because it blends the colors in a straight line.
To use a linear gradient:
- create a gradient with the
createLinearGradient
function - add at least two color stops at various positions between 0 and 1
- set the gradient as the fill style
The createLinearGradient
method takes the x and y coordinates of the start and ending points of a gradient.
The following example shows a horizontal linear gradient:
// Horizontal gradient
var grad = c.createLinearGradient(0,0,200,0);
grad.addColorStop(0, "white");
grad.addColorStop(1, "black");
c.fillStyle = grad;
c.fillRect(0,0,200,100);
This code produces the following result:
Strokes can also be drawn using a gradient. The following example strokes a rectangle with a gradient:
var grad = c.createLinearGradient(0,0,100,100);
grad.addColorStop(0, "white");
grad.addColorStop(1, "black");
c.lineWidth = 10;
c.strokeStyle = grad;
c.strokeRect(10,10,80,80);
This code produces the following result:
Radial Gradients
Radial gradients use the same color stop syntax as linear gradients, but have a different creation function. The
createRadialGradient
method takes six arguments: x1, y1, r1 x2, y2,
r2. The first three arguments define the start circle at x1, y1 with a radius
r1. The second three arguments define the ending circle at x2,
y2 and radius r2. In general the first circle should be inside the second circle.
var grad = c.createRadialGradient(45,45,10,52,50,30);
grad.addColorStop(0, "white");
grad.addColorStop(1, "black");
c.fillStyle = grad;
c.fillRect(10,10,80,80);
This code produces the following result:
Browser Support
The following table lists the attributes / methods related to this section and their browser compatibility:
Firefox | IE | Chrome | Opera | Safari | |
---|---|---|---|---|---|
Attributes / Methods | |||||
createLinearGradient() | |||||
createRadialGradient() |