HTML and CSS Reference
In-Depth Information
canvas.addEventListener('touchstart', function (event) {
event.preventDefault();
if (utils.containsPoint(ball.getBounds(), touch.x, touch.y)) {
log.value = "in ball: touchstart";
} else {
log.value = "canvas: touchstart";
}
}, false);
canvas.addEventListener('touchend', function (event) {
event.preventDefault();
log.value = "canvas: touchend";
}, false);
canvas.addEventListener('touchmove', function (event) {
event.preventDefault();
if (utils.containsPoint(ball.getBounds(), touch.x, touch.y)) {
log.value = "in ball: touchmove";
} else {
log.value = "canvas: touchmove";
}
}, false);
};
</script>
</body>
</html>
In the touch event listeners, we pass the
event
object to the handler function and call
event.preventDefault()
. This keeps the browser from continuing to process the event after the handler
has been executed. It also prevents the touch event's corresponding mouse event from being delivered,
which is the default behavior (though it is best not to rely on this).
Now that you understand the basics of the important interaction events, we'll move on to dragging.
Dragging an object
To drag an object around the canvas element, update the object's position to match the coordinates of the
mouse cursor. The programming is straight-forward: Capture a
mousedown
event when the cursor is over
the ball and set up a
mousemove
handler. This handler sets the ball's x and y coordinates to the current
mouse position. Then, on the
mouseup
event, remove that handler.
The next example,
03-mouse-move-drag.html
, should help make this clear:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mouse Move Drag</title>
<link rel="stylesheet" href="style.css">
</head>