HTML5 Guidelines for Web Developers

(coco) #1
5.4 Gradients 115

Figure 5.4 Linear gradient with four colors


First, context.createLinearGradient(x0, y0, x1, y1) creates a CanvasGradient
object and determines the direction of the gradient via the parameters x0, y0, x1,
y1. We still need to specify the color offsets in another step, so we save this object
in the variable linGrad:


var linGrad = context.createLinearGradient(
0,450,1000,450
);


The method addColorStop(offset, color)of the CanvasGradient object is the
next step and selects the desired colors and offsets on our imaginary gradient
line. Offset 0.0 represents the color at the point x0/y0 and offset 1.0 the color at
the end point x1/y1. All colors in between are divided up according to their offset,
and transitions between the individual stops are interpolated by the browser in
RGBA color space:


linGrad.addColorStop(0.0, 'red');
linGrad.addColorStop(0.5, 'yellow');

Free download pdf