This repository was archived by the owner on Dec 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy path06-z-sort.html
More file actions
98 lines (90 loc) · 2.72 KB
/
06-z-sort.html
File metadata and controls
98 lines (90 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<!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>