html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bouncing Ball Physics Animation</title>
<style>
body {
background: #222;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
canvas {
background: #333;
border-radius: 16px;
box-shadow: 0 8px 32px #000a;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Ball properties
let ball = {
x: canvas.width / 2,
y: 50,
radius: 25,
color: '#ff6f00',
vx: 2, // horizontal velocity
vy: 0, // vertical velocity
bounce: 0.75 // energy loss on bounce (0 < bounce < 1)
};
// Physics constants
const gravity = 0.6; // acceleration due to gravity
const floor = canvas.height - ball.radius;
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
// Simple shading for 3D effect
let grad = ctx.createRadialGradient(
ball.x - ball.radius/3, ball.y - ball.radius/3, ball.radius/4,
ball.x, ball.y, ball.radius
);
grad.addColorStop(0, '#fff7');
grad.addColorStop(0.3, ball.color);
grad.addColorStop(1, '#000a');
ctx.fillStyle = grad;
ctx.fill();
ctx.closePath();
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw floor
ctx.fillStyle = '#444';
ctx.fillRect(0, floor + ball.radius, canvas.width, canvas.height - floor);
drawBall();
// Physics
ball.vy += gravity; // gravity
ball.x += ball.vx;
ball.y += ball.vy;
// Bounce off floor
if (ball.y > floor) {
ball.y = floor;
ball.vy *= -ball.bounce;
// Friction on floor
ball.vx *= 0.98;
// Stop if very slow
if (Math.abs(ball.vy) < 1) ball.vy = 0;
if (Math.abs(ball.vx) < 0.1) ball.vx = 0;
}
// Bounce off walls
if (ball.x + ball.radius > canvas.width) {
ball.x = canvas.width - ball.radius;
ball.vx *= -ball.bounce;
}
if (ball.x - ball.radius < 0) {
ball.x = ball.radius;
ball.vx *= -ball.bounce;
}
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>