-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbounce.html
66 lines (50 loc) · 1.32 KB
/
bounce.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
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
<!DOCTYPE html>
<html lang="en">
<!-- See: https://rtestardi.github.io/pages/bounce.html -->
<head>
</head>
<body onload='Body()'>
<canvas id="canvas" width=512 height=256></canvas>
<script>
'use strict';
var ctx;
var x = 0; // the x position of the ball
var y = 0; // the y position of the ball
var xv = 1; // the x velocity of the ball
var yv = 1; // the y velociry of the ball
var width = 509; // the width of the playing field
var height = 251; // the height of the playing field
function Bounce()
{
// if we're going out-of-bounds in x...
if (x+xv < 0 || x+xv >= width) {
// bounce the x velocity
xv = -xv;
}
// if we're going out-of-bounds in y...
if (y+yv < 0 || y+yv >= height) {
// bounce the y velocity
yv = -yv;
}
// move the ball in x and y according to the x and y velocities
x += xv;
y += yv;
// draw the ball
ctx.beginPath();
ctx.arc(x, y, 4, 0, 2*Math.PI, false);
ctx.fill();
// run again in a millisecond
setTimeout(Bounce, 1);
}
// the user loaded the webpage; start the program
function Body()
{
// find out drawing canvas context
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
// start drawing the bouncing ball
setTimeout(Bounce, 1);
}
</script>
</body>
</html>