-
Notifications
You must be signed in to change notification settings - Fork 0
/
42-canvas-ball.html
53 lines (46 loc) · 1.23 KB
/
42-canvas-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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
<link rel="stylesheet" href="./lib/game.css" />
<style media="screen">
canvas { border: 1px solid #333 }
</style>
</head>
<canvas width="400" height="400"></canvas>
<body>
<script src="./lib/coffeescript.js"></script>
<script type="text/coffeescript">
###
Use the requestAnimationFrame technique that we saw in Chapter 14 and Chapter 16
to draw a box with a bouncing ball in it. The ball moves at a constant speed and
bounces off the box’s sides when it hits them.
###
canvas = document.querySelector 'canvas'
ctx = canvas.getContext '2d'
width = canvas.width
height = canvas.height
lastTime = null
frame = (time) ->
if lastTime != null
updateAnimation Math.min(100, time - lastTime) / 1000
lastTime = time
requestAnimationFrame frame
requestAnimationFrame frame
pos = { x: width/2, y: height/2 }
speed = { x: 1, y: 3 }
r = 10
updateAnimation = (step) ->
# Your code here
pos.x += speed.x
pos.y += speed.y
speed.x = 0 - speed.x if (pos.x < r || pos.x + r > width)
speed.y = 0 - speed.y if (pos.y < r || pos.y + r > height)
ctx.clearRect(0, 0, 400, 400)
ctx.beginPath()
ctx.arc(pos.x, pos.y, r, r, 0, Math.PI * 2)
ctx.fill()
</script>
</body>
</html>