Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
88 lines (78 sloc) 2.26 KB
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Trees 1</title>
<link rel="stylesheet" href="../include/style.css">
<style>
#canvas {
background-color: #000000;
}
</style>
</head>
<body>
<header>
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
</header>
<canvas id="canvas" width="400" height="400"></canvas>
<aside>Press up and down arrow keys to move through scene.</aside>
<script src="../include/utils.js"></script>
<script src="./classes/tree.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
trees = [],
numTrees = 100,
fl = 250,
vpX = canvas.width / 2,
vpY = canvas.height / 2,
floor = 200,
vz = 0,
friction = 0.98;
for (var tree, i = 0; i < numTrees; i++) {
tree = new Tree();
tree.xpos = Math.random() * 2000 - 1000;
tree.ypos = floor;
tree.zpos = Math.random() * 10000;
trees.push(tree);
}
window.addEventListener('keydown', function (event) {
if (event.keyCode === 38) { //up
vz -= 1;
} else if (event.keyCode === 40) { //down
vz += 1;
}
}, false);
function move (tree) {
tree.zpos += vz;
if (tree.zpos < -fl) {
tree.zpos += 10000;
}
if (tree.zpos > 10000 - fl) {
tree.zpos -= 10000;
}
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>