HTML and CSS Reference
In-Depth Information
var linearGradient = ctx.createLinearGradient(x0, y0, x1, y1);
var radialGradient = ctx.createRadialGradient(x0, y0, r0, x1, y1, r1);
Linear gradients start at x0 , y0 and go until x1 , y1 . They are drawn as an infinitely-wide band that is per-
pendicular to the line created by the passed-in points.
Radial gradients are generated as a cone created between the two circles defined by the passed-in parameters.
Areas outside of both circles are transparent. If you just want to create a single circular gradient, you can set the
first radius to 0 and both points x0 , y0 and x1 , y1 to be the same point.
After you create a gradient, you need to add color stops to it. These define the color at a specific percentage
of the way from the start to the end of the gradient. To add a stop, you need to call addColorStop on the
gradient and pass a number from 0 to 1 that represents the position of the stop and the color:
gradient.addColorStop(position, color);
For example, to create a gradient that goes from black to white at the midpoint and then back to black, you
could write
linearGradient.addColorStop(0,"#000");
linearGradient.addColorStop(0.5,"#FFF");
linearGradient.addColorStop(1,"#000");
You can use any valid CSS color definition to pass in as the second parameter to addColorStop .
The last stroke or fill style you can create is a pattern. A pattern is an image repeated over the area of the fill
and is created by calling
var pattern = ctx.createPattern(sourceImage,repeatString);
sourceImage can be an <img> element; this includes objects created with new Image() , a <video>
element, or a <canvas> element. repeatString is one of the following values: "repeat" , "repeat-
x" , "repeat-y" , or "no-repeat" . You should recognize these strings as the repeat values you can set on
a backgroundImage in CSS. They map to the pattern repeated in both directions, repeated horizontally only,
repeated vertically only, and not repeated at all.
Listing 15-4 shows an example of both types of gradients created along with a simple pattern generated from
an offscreen <canvas> element. The result is shown in Figure 15-3 .
 
 
Search WWH ::




Custom Search