-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
68 lines (55 loc) · 1.42 KB
/
Copy pathindex.html
File metadata and controls
68 lines (55 loc) · 1.42 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
<!DOCTYPE html>
<html>
<head>
<title>Bouncing Ball</title>
<style>
canvas {
background: #cccccc;
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Coordinate system conversion
const width = canvas.width;
const height = canvas.height;
// Ball properties
let rx = 0.480, ry = 0.860; // position
let vx = 0.015, vy = 0.023; // velocity
let radius = 0.05; // radius (scaled)
// Function to convert StdDraw coordinates to canvas coordinates
function xToCanvas(x) {
return (x + 1) / 2 * width;
}
function yToCanvas(y) {
return height - (y + 1) / 2 * height;
}
function drawBall() {
ctx.clearRect(0, 0, width, height);
// Update physics
if (Math.abs(rx + vx) > 1 - radius) vx = -vx;
if (Math.abs(ry + vy) > 1 - radius) vy = -vy;
rx += vx;
ry += vy;
// Draw ball
ctx.fillStyle = "black";
ctx.beginPath();
ctx.arc(
xToCanvas(rx),
yToCanvas(ry),
radius * width / 2,
0,
Math.PI * 2
);
ctx.fill();
requestAnimationFrame(drawBall);
}
drawBall();
</script>
</body>
</html>