HTML and CSS Reference
In-Depth Information
The code in the previous listing uses the 2D context object to
generate a linear gradient object to which you can then apply
colour stops. The arguments are the starting point of the gra-
dient, x1 and y1, and the endpoint of the gradient, x2 and y2.
In this example, I'm telling the gradient to start in the top left
and finish at the bottom left of the canvas. This creates a gradi-
ent that runs vertically ( Figure 5.6 ).
Radial gradients are very similar, except the createRadialGradient
takes the radius after each coordinate:
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d'),
gradient = ctx.createRadialGradient(canvas.width/2,
canvas.height/2, 0,
canvas.width/2, canvas.height/2, 150);
gradient.addColorStop(0, '#fff');
gradient.addColorStop(1, '#000');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.width);
The only difference is the kind of gradient that's created. In this
example, I've moved the first point of the gradient to start in the
centre of the canvas starting with a radius of zero. The gradi-
ent uses a radius of 150 pixels, but notice that it also starts in
the same place: canvas.width/2 , canvas.height/2 . This is so my
example creates a smooth, circular gradient ( Figure 5.7 ).
Patterns are even easier to use. You need a source, and then
you can drop the source element into the createPattern method
and use the result as the fillStyle . The only caveat is that the
element, in the case of images and videos, must have finished
loading to capture the source properly.
To c r e a t e t h e e f e c t s h To w in i in Figure 5.8 (a tiled image across the
back of the canvas), first stretch the canvas over the size of the
window. Then dynamically create an image and, when it fires the
load event, use the image as the source of a repeating pattern:
var canvas = document.querySelector('canvas'),
img = document.createElement('img'),
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
img.onload = function () {
FIguRE 5.6 A vertical
gradient on a canvas element.
FIguRE 5.7 This radial
gradient starts and ends at the
same point, but the ending
radius is much greater, causing
a smooth, circular gradient.
 
Search WWH ::




Custom Search