HTML and CSS Reference
In-Depth Information
ball.x = mouse.x;
ball.y = mouse.y;
}
function checkBoundaries () {
var left = 0,
right = canvas.width,
top = 0,
bottom = canvas.height;
vy += gravity;
ball.x += vx;
ball.y += vy;
//boundary detect and bounce
if (ball.x + ball.radius > right) {
ball.x = right - ball.radius;
vx *= bounce;
} else if (ball.x - ball.radius < left) {
ball.x = left + ball.radius;
vx *= bounce;
}
if (ball.y + ball.radius > bottom) {
ball.y = bottom - ball.radius;
vy *= bounce;
} else if (ball.y - ball.radius < top) {
ball.y = top + ball.radius;
vy *= bounce;
}
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
if (!isMouseDown) {
checkBoundaries();
}
ball.draw(context);
}());
};
</script>
</body>
</html>
As you can see, we've moved all the boundary checking code into the function
checkBoundaries
and
added the mouse event handlers. We've also declared the variable
isMouseDown
that is updated by the
handlers to keep track of the mouse button stateāso we check only the boundaries when the mouse is
not
pressed.
If you run this example, you can see the problem when you stop dragging the ball. Yes, the dragging
works, but the motion code continues working at the same time. You need some way of switching on or off
the motion code, so that it doesn't happen while you're dragging.