Skip to content

Commit 0817ce8

Browse files
完成demo ch09/01-object-hit-test.html 的改写
1 parent 68bdf3f commit 0817ce8

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<!doctype html>
2+
<html>
3+
<head>
4+
<meta charset="utf-8">
5+
<title>Bobbing 1</title>
6+
<link rel="stylesheet" href="../include/style.css">
7+
<style type="text/css">
8+
#canvas {
9+
background: #fff;
10+
}
11+
</style>
12+
</head>
13+
<body>
14+
<header>
15+
Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
16+
</header>
17+
<canvas id="canvas" width="640" height="340"></canvas>
18+
19+
<script type="module">
20+
import {captureMouse, rectContainsPoint} from '../include/utils.js'
21+
import Ball from './classes/ball.js'
22+
import Box from './classes/box.js'
23+
24+
window.onload = function () {
25+
const canvas = document.getElementById('canvas'),
26+
context = canvas.getContext('2d'),
27+
{width, height} = canvas,
28+
mouse = captureMouse(canvas);
29+
30+
let centerBall = new Ball(),
31+
centerBox = new Box(80, 80, 'transparent');
32+
33+
centerBall.x = width / 2;
34+
centerBall.y = height / 2;
35+
centerBox.x = centerBall.x - 40;
36+
centerBox.y = centerBall.y - 40;
37+
38+
let mouseBall = new Ball(),
39+
mouseBox = new Box(80, 80, 'transparent');
40+
41+
(function draw(){
42+
window.requestAnimationFrame(draw);
43+
context.clearRect(0, 0, width, height);
44+
45+
mouseBall.x = mouse.x;
46+
mouseBall.y = mouse.y;
47+
mouseBox.x = mouse.x - 40;
48+
mouseBox.y = mouse.y - 40;
49+
50+
if (rectContainsPoint(centerBox, mouseBox)) {
51+
console.log('hit!')
52+
} else {
53+
console.log('not hit!')
54+
}
55+
56+
centerBall.draw(context);
57+
centerBox.draw(context);
58+
mouseBall.draw(context);
59+
mouseBox.draw(context);
60+
}())
61+
}
62+
</script>
63+
</body>
64+
</html>

0 commit comments

Comments
 (0)