Here's a complete HTML file with inline CSS and JavaScript that creates a physics-based ball rolling animation:
<!DOCTYPE html>
<html>
<head>
<title>Ball Rolling Down Hill</title>
<style>
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
canvas {
border: 1px solid #333;
background-color: #87ceeb;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Physics constants
const GRAVITY = 0.5; // Gravity force
const FRICTION = 0.98; // Friction coefficient (0-1)
const BOUNCE = 0.7; // Energy loss on bounce
const BALL_RADIUS = 15;
// Array to store all active balls
let balls = [];
// Array to store hill points
let hillPoints = [];
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
this.vx = 0; // Velocity x
this.vy = 0; // Velocity y
this.radius = BALL_RADIUS;
}
// Draw ball with 3D gradient effect
draw() {
const gradient = ctx.createRadialGradient(
this.x - this.radius/2,
this.y - this.radius/2,
this.radius/4,
this.x,
this.y,
this.radius
);
gradient.addColorStop(0, '#ff9999');
gradient.addColorStop(1, '#ff0000');
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = gradient;
ctx.fill();
ctx.closePath();
}
// Update ball physics
update() {
// Find the hill height at current x position
const hillY = getHillHeight(this.x);
// Calculate the slope angle at current position
const nextHillY = getHillHeight(this.x + 1);
const slopeAngle = Math.atan2(nextHillY - hillY, 1);
// Apply gravity based on slope
// Gravity component along the slope: g * sin(θ)
const gravityForce = GRAVITY * Math.sin(slopeAngle);
// Update velocity
this.vx += gravityForce;
this.vy += GRAVITY * Math.cos(slopeAngle);
// Apply friction to velocity
this.vx *= FRICTION;
this.vy *= FRICTION;
// Update position
this.x += this.vx;
this.y += this.vy;
// Collision with hill
if (this.y + this.radius > hillY) {
this.y = hillY - this.radius;
// Bounce (reduce velocity in y direction)
this.vy = -this.vy * BOUNCE;
}
// Keep ball within canvas bounds
if (this.x < this.radius) {
this.x = this.radius;
this.vx = -this.vx * BOUNCE;
}
if (this.x > canvas.width - this.radius) {
this.x = canvas.width - this.radius;
this.vx = -this.vx * BOUNCE;
}
}
}
// Generate random hill landscape
function generateHill() {
hillPoints = [];
const segments = 20;
const segmentWidth = canvas.width / segments;
let lastY = canvas.height * 0.7;
for (let i = 0; i <= segments; i++) {
const x = i * segmentWidth;
// Generate random height with smooth transitions
const y = lastY + (Math.random() - 0.5) * 50;
// Keep hill within reasonable bounds
lastY = Math.max(canvas.height * 0.4, Math.min(canvas.height * 0.9, y));
hillPoints.push({ x, y: lastY });
}
}
// Get hill height at specific x position (linear interpolation)
function getHillHeight(x) {
for (let i = 0; i < hillPoints.length - 1; i++) {
if (x >= hillPoints[i].x && x <= hillPoints[i + 1].x) {
const t = (x - hillPoints[i].x) / (hillPoints[i + 1].x - hillPoints[i].x);
return hillPoints[i].y + t * (hillPoints[i + 1].y - hillPoints[i].y);
}
}
return hillPoints[hillPoints.length - 1].y;
}
// Draw the hill
function drawHill() {
ctx.beginPath();
ctx.moveTo(0, canvas.height);
ctx.lineTo(0, hillPoints[0].y);
for (let i = 0; i < hillPoints.length; i++) {
ctx.lineTo(hillPoints[i].x, hillPoints[i].y);
}
ctx.lineTo(canvas.width, hillPoints[hillPoints.length - 1].y);
ctx.lineTo(canvas.width, canvas.height);
ctx.closePath();
ctx.fillStyle = '#90ee90';
ctx.fill();
}
// Handle click to add new ball
canvas.addEventListener('click', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
balls.push(new Ball(x, y));
});
// Animation loop
function animate() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw hill
drawHill();
// Update and draw all balls
balls = balls.filter(ball => {
ball.update();
ball.draw();
// Remove balls that are too far off-screen
return ball.y < canvas.height + ball.radius;
});
requestAnimationFrame(animate);
}
// Initialize
generateHill();
// Add initial ball
balls.push(new Ball(canvas.width/2, 50));
animate();
</script>
</body>
</html>
This code creates a complete physics-based animation with the following features:
-
Visuals:
- A canvas with a sky blue background
- A randomly generated bumpy hill in green
- Balls with a red gradient giving a 3D appearance
-
Physics Implementation:
- Gravity affects the balls based on the slope angle
- Friction slows down the balls' movement
- Bounce effect when balls hit the hill
- Collision detection with hill surface and canvas boundaries
-
Interactivity:
- Click anywhere on the canvas to drop a new ball
- Multiple balls can exist simultaneously
- Balls are removed when they fall off the bottom of the screen
-
Key Physics Calculations (explained in comments):
- Slope angle calculation using arctangent
- Gravity decomposition into components along and perpendicular to the slope
- Friction applied as a velocity multiplier
- Bounce implemented with energy loss
-
Performance:
- Uses requestAnimationFrame for smooth animation
- Efficient hill height interpolation
- Automatic cleanup of off-screen balls
To use this, simply save it as an HTML file and open it in a modern web browser. You can click anywhere on the canvas to add new balls, and they'll roll down the hill following the physics rules implemented in the code.
The hill is randomly generated each time the page loads, creating a different landscape for the balls to roll on. The physics model, while simplified, provides a realistic-feeling simulation of balls rolling down a bumpy hill.