HTML and CSS Reference
In-Depth Information
The
compareFunction
parameter is a function that in turn takes two arguments, and these are the array
elements that are compared as it iterates over the entire collection. How the array is ordered is determined
by the numeric return value of the
compareFunction
when passed successive elements using the
following rules:
Let
n = compareFunction(a, b)
,
If
n
is less than 0, sort element
a
to a lower index than element
b
.
If
n
returns 0, leave element
a
and element
b
unchanged.
If
n
is greater than 0, sort element
b
to a lower index than element
a
.
For example, to sort an array of numbers in ascending order:
var arr = [3, 5, 1, 4, 2];
arr.sort(function (a, b) { return (a - b); });
console.log(arr); //prints [1, 2, 3, 4, 5]
In terms of 3D depth ordering, index 0 is the bottom, and any objects with a higher number appear in front
of objects with a lower number. You want to sort the array of objects from the highest depth (farthest away)
to lowest (closest). The following code defines our sort function, and then orders the
balls
array:
function zSort (a, b) {
return (b.zpos - a.zpos);
}
balls.sort(zSort);
This sorts the array based on the
zpos
property of each object, in reverse numerical order—in other
words, from high to low. The result is that the ball that is farthest away (highest
zpos
value) is first in the
array and therefore drawn first to the canvas element. The closest ball is the last element in the array and
drawn on top of every other ball.
Once you add this function to previous example, you need to call it
before
you draw the balls:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(move);
balls.sort(zSort);
balls.forEach(draw);
}());
The rest of the code remains the same as the previous exercise. The full listing can be found in document
06-z-sort.html
.