HTML and CSS Reference
In-Depth Information
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Point Hit Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<textarea id="log"></textarea>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
mouse = utils.captureMouse(canvas),
log = document.getElementById('log'),
ball = new Ball();
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.draw(context);
canvas.addEventListener('mousemove', function () {
if (utils.containsPoint(ball.getBounds(), mouse.x, mouse.y)) {
log.value = "Hit!";
} else {
log.value = '';
}
}, false);
};
</script>
</body>
</html>
This uses the mouse cursor as the point which the ball hit tests against. As you move the mouse close to
the ball, you will see that it probably starts registering a hit before you actually touch the shape, especially
if you come at it from a corner, as shown in Figure 9.6. Try it again with a square and it should be perfectly
accurate. So again, this method seems to be useful only for rectangle-shaped objects.
Search WWH ::




Custom Search