forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17_3_a_bouncing_ball.html
More file actions
36 lines (31 loc) · 888 Bytes
/
17_3_a_bouncing_ball.html
File metadata and controls
36 lines (31 loc) · 888 Bytes
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
<!doctype html>
<canvas width="400" height="400"></canvas>
<script>
let cx = document.querySelector("canvas").getContext("2d");
let lastTime = null;
function frame(time) {
if (lastTime != null) {
updateAnimation(Math.min(100, time - lastTime) / 1000);
}
lastTime = time;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
let x = 100, y = 300;
let radius = 10;
let speedX = 100, speedY = 60;
function updateAnimation(step) {
cx.clearRect(0, 0, 400, 400);
cx.strokeStyle = "blue";
cx.lineWidth = 4;
cx.strokeRect(25, 25, 350, 350);
x += step * speedX;
y += step * speedY;
if (x < 25 + radius || x > 375 - radius) speedX = -speedX;
if (y < 25 + radius || y > 375 - radius) speedY = -speedY;
cx.fillStyle = "red";
cx.beginPath();
cx.arc(x, y, radius, 0, 7);
cx.fill();
}
</script>