Theme: 2D Physics Simulation
Language: JavaScript (no external libraries)
Objective: Simulate a bouncing ball affected by gravity inside a rectangular canvas, ensuring smooth animation and basic collision response.
Constraints:
The ball should bounce off the walls with realistic behavior (consider energy loss on impact using friction).
Gravity should affect the ball's trajectory over time.
No external dependencies or libraries are allowed.
Use a <canvas> element for rendering.
Assistant
Here's a simple 2D physics simulation of a bouncing ball affected by gravity inside a rectangular canvas using JavaScript and the <canvas> element. The simulation includes realistic bouncing behavior with energy loss on impact due to friction.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bouncing Ball Simulation</title>
<style>
body {
margin: 0;
overflow: hidden; /* Hide scrollbars */
}
canvas {
display: block; /* Removes padding around the canvas */
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
// Get the canvas element and set its dimensions to fill the window
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Set canvas dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Ball properties
const ball = {
x: canvas.width / 2, // Starting x position
y: canvas.height / 2, // Starting y position
radius: 20, // Ball radius
color: 'blue', // Ball color
vx: 2, // Initial horizontal velocity
vy: 0, // Initial vertical velocity
gravity: 0.5, // Acceleration due to gravity
friction: 0.9, // Energy loss on impact
bounceEfficiency: 0.7 // Coefficient of restitution
};
// Animation loop
function animate() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the ball
drawBall();
// Update ball position
updateBall();
// Request the next frame
requestAnimationFrame(animate);
}
// Function to draw the ball
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = ball.color;
ctx.fill();
ctx.closePath();
}
// Function to update the ball's position and handle collisions
function updateBall() {
// Apply gravity to vertical velocity
ball.vy += ball.gravity;
// Apply friction to horizontal velocity
ball.vx *= ball.friction;
// Update position
ball.x += ball.vx;
ball.y += ball.vy;
// Collision detection with walls
// Bottom wall
if (ball.y + ball.radius > canvas.height) {
ball.y = canvas.height - ball.radius;
ball.vy *= -ball.bounceEfficiency; // Reverse velocity with energy loss
ball.vx *= ball.friction; // Apply friction
}
// Top wall
if (ball.y - ball.radius < 0) {
ball.y = ball.radius;
ball.vy *= -ball.bounceEfficiency;
}
// Right wall
if (ball.x + ball.radius > canvas.width) {
ball.x = canvas.width - ball.radius;
ball.vx *= -ball.bounceEfficiency;
}
// Left wall
if (ball.x - ball.radius < 0) {
ball.x = ball.radius;
ball.vx *= -ball.bounceEfficiency;
}
}
// Start the animation
animate();
// Handle window resize
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
Explanation
HTML Structure
The <canvas> element is used for rendering the 2D animation.
The <script> tag contains all the JavaScript code required for the simulation.
The <style> section is used to remove default margins and hide scrollbars to make the canvas fill the entire browser window.
JavaScript Code
Canvas Setup
Canvas and Context: We get the canvas element by its ID and obtain the 2D rendering context.
Copy the Code: Copy the entire HTML code provided above.
Create an HTML File: Paste the code into a new text file and save it with a .html extension, e.g., bouncing_ball.html.
Open in Browser: Open the HTML file in a modern web browser like Chrome, Firefox, or Edge.
Interact: You should see a blue ball bouncing inside the browser window, affected by gravity and losing energy upon each bounce.
Customization
Ball Color: Change the color property in the ball object.
Gravity Strength: Modify the gravity property to make gravity stronger or weaker.
Friction: Adjust the friction property to simulate different levels of air resistance.
Bounce Efficiency: Change bounceEfficiency to control how much energy the ball retains after bouncing.
Ball Size: Alter the radius property to make the ball larger or smaller.
Initial Velocity: Modify vx and vy for different starting motions.
Feel free to experiment with the properties to see how they affect the simulation. This basic framework can be expanded to include more balls, user interaction, or additional physics features.