HTML and CSS Reference
In-Depth Information
example, we remove only one element: the one at the current index. When you test this, you won't be
aware of their removal—which is a good thing—but you can be confident the balls are not lingering around
outside the canvas.
Notice that the while loop in this example is a little different from previous examples:
var i = balls.length;
while (i--) {
draw(balls[i], i);
}
This causes the while loop to iterate backward through the array instead of forward. This is necessary
because, when you splice the array, the indexing will change. When you increment i , you will skip over
one of the elements. Going backward handles this, as long as nothing is added to the beginning of the
array during iteration.
Finally, after splicing an element out of the array, we check to see whether the array length is zero, to
display a message that all the balls have been removed from the animation.
Regenerating objects
The next method for handling an object that leaves the defined boundaries is to regenerate it, or more
precisely, to reposition it. The basic idea is that when an object has moved off the canvas and is no longer
necessary, you can place it at a new position as if it were a brand-new object. This provides you with a
steady stream of objects without the worry about having too many objects slowing down the browser,
because there will be a set number.
This technique is useful for creating fountains and other particle effects, where you have a stream of
objects spraying constantly. The particles go off the canvas and are reintroduced at the source point of the
stream.
The mechanics of regeneration are similar to removal: You wait until the object is out of bounds, but
instead of removing it, you move it.
Let's dive right in by making a fountain. For the fountain particles, use the same Ball class, but make
them very small by setting their radius of just 2 pixels across, and give each a random color. The source of
the fountain will be a point at the bottom-center of the canvas element. Every particle will originate there,
and when they move off the canvas, they'll be repositioned there. Also, each particle starts with a random
negative y velocity and a (small) random x velocity. The particles shoot upward, moving slightly to the left
or the right, and also react to gravity. When a particle regenerates, its position and velocity will be reset.
Here's the document 02-fountain.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Fountain</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
 
Search WWH ::




Custom Search