-
Notifications
You must be signed in to change notification settings - Fork 96
/
bouncing ball.html
38 lines (38 loc) · 1.03 KB
/
bouncing ball.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="box" style="width: 500px;height: 500px;position: relative;overflow: hidden;background: #ccc;">
<div id="ball" style="width: 10px;height: 10px;border-radius: 5px;position: absolute;background: red;"></div>
</div>
<script>
function fun(v) {
let Vx = Math.random()*v;
let Vy = Math.sqrt(v*v - Vx*Vx);
let startX = Math.random()*490;
let startY = Math.random()*490;
const ball = document.getElementById('ball');
Math.random() > 0.5 && (Vx *= -1);
Math.random() > 0.5 && (Vy *= -1);
ball.style.left = startX + 'px';
ball.style.top = startY + 'px';
function animate(){
if(startX >= 490 || startX <= 0)
Vx = -Vx;
startX += Vx;
if(startY >= 490 || startY <= 0)
Vy = -Vy;
startY += Vy;
ball.style.left = startX + 'px';
ball.style.top = startY + 'px';
window.requestAnimationFrame(animate);
}
window.requestAnimationFrame(animate);
}
fun(5);
</script>
</body>
</html>