Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
99 lines (90 sloc) 2.72 KB
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Z-Sort</title>
<link rel="stylesheet" href="../include/style.css">
</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>
<script src="../include/utils.js"></script>
<script src="./classes/ball3d.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
balls = [],
numBalls = 50,
fl = 250,
vpX = canvas.width / 2,
vpY = canvas.height / 2,
top = -100,
bottom = 100,
left = -100,
right = 100,
back = 100,
front = -100;
for (var ball, i = 0; i < numBalls; i++) {
ball = new Ball3d(15);
ball.vx = Math.random() * 10 - 5;
ball.vy = Math.random() * 10 - 5;
ball.vz = Math.random() * 10 - 5;
balls.push(ball);
}
function move (ball) {
ball.xpos += ball.vx;
ball.ypos += ball.vy;
ball.zpos += ball.vz;
if (ball.xpos + ball.radius > right) {
ball.xpos = right - ball.radius;
ball.vx *= -1;
} else if (ball.xpos - ball.radius < left) {
ball.xpos = left + ball.radius;
ball.vx *= -1;
}
if (ball.ypos + ball.radius > bottom) {
ball.ypos = bottom - ball.radius;
ball.vy *= -1;
} else if (ball.ypos - ball.radius < top) {
ball.ypos = top + ball.radius;
ball.vy *= -1;
}
if (ball.zpos + ball.radius > back) {
ball.zpos = back - ball.radius;
ball.vz *= -1;
} else if (ball.zpos - ball.radius < front) {
ball.zpos = front + ball.radius;
ball.vz *= -1;
}
if (ball.zpos > -fl) {
var scale = fl / (fl + ball.zpos);
ball.scaleX = ball.scaleY = scale;
ball.x = vpX + ball.xpos * scale;
ball.y = vpY + ball.ypos * scale;
ball.visible = true;
} else {
ball.visible = false;
}
}
function zSort (a, b) {
return (b.zpos - a.zpos);
}
function draw (ball) {
if (ball.visible) {
ball.draw(context);
}
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
balls.forEach(move);
balls.sort(zSort);
balls.forEach(draw);
}());
};
</script>
</body>
</html>