HTML and CSS Reference
In-Depth Information
function trackVelocity () {
vx = ball.x - oldX;
vy = ball.y - oldY;
oldX = ball.x;
oldY = ball.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) {
trackVelocity();
} else {
checkBoundaries();
}
ball.draw(context);
}());
};
</script>
</body>
</html>
Now that is interactive and a good example of a real-world physics animation created using event handlers
and JavaScript. It feels like you're throwing something around. Play around with the gravity and bounce
variables, and if you want, add friction to simulate some atmosphere.
Search WWH ::




Custom Search