HTML and CSS Reference
In-Depth Information
var scale = fl / (fl + tree.zpos);
tree.scaleX = tree.scaleY = scale;
tree.x = vpX + tree.xpos * scale;
tree.y = vpY + tree.ypos * scale;
tree.alpha = scale;
}
function zSort (a, b) {
return (b.zpos - a.zpos);
}
function draw (tree) {
tree.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
trees.forEach(move);
vz *= friction;
trees.sort(zSort);
trees.forEach(draw);
}());
};
</script>
</body>
</html>
There is only a single variable for z velocity, because the trees won't move on the x or y axis, and all move
in unison on the z-axis. We attached a keydown event listener to the document, which increments or
decrements vz accordingly. Applying a little friction in the drawFrame function keeps the speed from
increasing infinitely, and slows you down if no key is pressed.
The code then loops through each tree, updating its z position with the current z velocity. Then it checks
whether a tree has gone behind you. If so, rather than making it invisible, it moves the tree 10,000 pixels
into the z axis. Likewise, if it has gone past 10,000 - fl , it moves the tree back 10,000.
You then do the standard perspective actions. Here, we also add another little extra to enhance the illusion
of depth:
tree.alpha = scale;
This sets the transparency of the tree in relation to its depth on the z-axis. The farther away it goes, the
more it fades out. This is atmospheric perspective, simulating the effect of the atmosphere between the
viewer and the object. This is particularly effective when you have objects moving way out in the distance,
as in this example. The effect is applied to the canvas context within the tree's draw method:
context.strokeStyle = utils.colorToRGB(this.color, this.alpha);
This specific calculation for transparency gives the effect of a dark, spooky night. You might want to try
something like the following:
Search WWH ::




Custom Search