168 Chapter 5—Canvas
radgrad.addColorStop(1.0,'rgba(0,0,0,0)');
// draw circle
context.save();
context.translate(cx,cy);
context.beginPath();
context.moveTo(0+r,0);
context.arc(0,0,r,0,Math.PI*2.0,0);
context.fillStyle = radgrad;
context.fill();
context.restore();
}
};
drawCircles(); // draw first set of spheres
// start/stop animation at pulse speed
var pulse = 60;
var running = null;
canvas.onclick = function() {
if (running) {
window.clearInterval(running);
running = null;
}
else {
running = window.setInterval(
"drawCircles()",60000/pulse
);
}
};
After defining canvas, context, and some other variables, the proper work starts
with the function drawCircles(). A semitransparent white rectangle fades exist-
ing content from previous drawCircles() calls, and then the for loop draws new
spheres. The position of each sphere and its radius are randomized once again
with Math.random(), placing the center in each case into the canvas area and lim-
iting the radius to a tenth of the canvas width.
To make sure the circles look like spheres, we create a radial gradient. Its ge-
ometry consists in a light spot at the top right and the total circle. The choice of
increment of the for loop reflects the desire to have colors in HSL color space
as colorStops of the gradient. With each loop, the color angle increases by 15°,
causing the color change from red to green to blue and back to red.
We can then in each case derive pairs of matching colors from the lightness:
The first one represents the light spot and the second one the darker color near
the sphere’s edge. The third call of addColorStop() causes the very edges of the
sphere to fade to transparent black. We create a total of 24 spheres in this way; to
make things clearer, the spheres’ color pairs are shown in Figure 5.39.