HTML and CSS Reference
In-Depth Information
ball.draw(context);
canvas.addEventListener('mousedown', function () {
if (utils.containsPoint(ball.getBounds(), mouse.x, mouse.y)) {
log.value = "in ball: mousedown";
} else {
log.value = "canvas: mousedown";
}
}, false);
canvas.addEventListener('mouseup', function () {
if (utils.containsPoint(ball.getBounds(), mouse.x, mouse.y)) {
log.value = "in ball: mouseup";
} else {
log.value = "canvas: mouseup";
}
}, false);
canvas.addEventListener('mousemove', function () {
if (utils.containsPoint(ball.getBounds(), mouse.x, mouse.y)) {
log.value = "in ball: mousemove";
} else {
log.value = "canvas: mousemove";
}
}, false);
};
</script>
</body>
</html>
This sets up listeners on the canvas element for the three mouse events we've talked about: mousedown ,
mouseup , and mousemove . After detecting a mouse event, the handler functions test whether the mouse
coordinates fall within the bounds of the ball, using Ball.getBounds and utils.containsPoint , and it
prints a message. Play around with this example to see exactly when and where particular mouse events
occur. Here are some things to notice:
You get the canvas events no matter where the mouse is, even if it's over the ball.
You won't get a mouseup event without first getting a mousedown event.
Using touch events
Throughout the topic examples, we use a mouse for user input because it's assumed that you are on a
development machine with a keyboard and mouse that is handy. But with the proliferation of touch screen
devices, it's not only possible, but quite probable, you'll need to capture touch events from the user.
Although touch screens and mice are different devices, thankfully for us, capturing touch events is similar
to capturing mouse events from the DOM.
The touch events most compatible with the examples in this topic and their mouse event counterparts are
touchstart , touchend , and touchmove . The touchstart event is fired on the contact of first touch,
touchend when a finger leaves the surface, and touchmove when the finger is dragged on the surface.
For more details about touch events, browse the W3C Specification at http://www.w3.org/TR/touch-
 
Search WWH ::




Custom Search