HTML and CSS Reference
In-Depth Information
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(move);
balls.forEach(draw);
}());
};
</script>
</body>
</html>
When you run this script, you'll see the balls fill up the space between the six boundaries, as shown in
Figure 15-5, and you can get an idea of the shape of this space.
Figure 15-5. Bouncing 3D balls
Z-sorting
Now, this addition of multiple objects brings up an issue lacking in the code you have so far—something
called z-sorting. Z-sorting is how objects are sorted on the z-axis, or which one goes in front of another
one. If you look closely at the ball outlines, you can see which ball is on top of which. This pretty much
ruins the whole 3D effect, because smaller objects are now appearing in front of larger ones. But we can
fix the order the balls are drawn to the canvas element by applying z-sorting.
Our code draws the balls in the order they are positioned in the balls array. In the prior example, that
order is determined when the balls are first initialized and added to the array. So if we want to draw the
balls according to their position on the z-index, we need to reorder them accordingly. To reorder an array
in JavaScript, we need to define a function to sort it.
JavaScript arrays have a sort method that is defined as Array.sort([compareFunction]) . The
method has an optional function parameter that defines the sort order by comparing each element. If this
argument omitted, the array is sorted alphabetically by the element names.
 
Search WWH ::




Custom Search