-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfreefall.js
More file actions
54 lines (47 loc) · 1.26 KB
/
freefall.js
File metadata and controls
54 lines (47 loc) · 1.26 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
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var g = 0.1;
var radius = 10;
var color;
var balls;
var numBalls = 6;
//window.onload = init;
function init() {
balls = new Array();
for (var i = 0; i < numBalls; i++) {
var ball = new Ball(Math.random() * 25, getRandomColor());
ball.x = Math.random() * 300; //x axis positions are random
ball.y = 0;
ball.vx = 0;
ball.vy = 0;
ball.draw(context);
balls.push(ball);
}
setInterval(onEachStep, 1000 / 60); // 60 fps
}
function onEachStep() {
context.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < numBalls; i++) {
var ball = balls[i];
ball.vy += g;
ball.x += ball.vx;
ball.y += ball.vy;
if (ball.y > canvas.height - radius) {
ball.y = canvas.height - radius;
ball.vy *= -0.3;
}
if (ball.x > canvas.width + radius) {
ball.x = -radius;
}
ball.draw(context);
}
}
//random color function
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}