Sure! Below is a complete example of a 2D particle simulator in JavaScript using HTML5 Canvas. It simulates 100 particles inside a square container, each represented as a small circle (5 pixels diameter). Particles have random initial positions, velocities, and directions. They collide elastically with each other (like billiard balls) and bounce off the walls (like a pool table).
Features:
- 100 particles initialized at random positions.
- Each particle has a random velocity and direction.
- Elastic collisions between particles (equal mass).
- Elastic collisions with container walls.
- Particles are drawn as circles with 5 pixels diameter.
- Smooth animation using
requestAnimationFrame.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>2D Particle Simulator</title>
<style>
body {
margin: 0;
background: #222;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
canvas {
background: #fff;
border: 2px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
(() => {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
const PARTICLE_COUNT = 100;
const PARTICLE_RADIUS = 2.5; // 5 pixels diameter
const PARTICLE_DIAMETER = PARTICLE_RADIUS * 2;
// Particle class
class Particle {
constructor(x, y, vx, vy) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.radius = PARTICLE_RADIUS;
this.mass = 1; // unit mass
}
draw(ctx) {
ctx.beginPath();
ctx.fillStyle = '#0077ff';
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
}
update() {
this.x += this.vx;
this.y += this.vy;
}
checkWallCollision() {
// Left wall
if (this.x - this.radius < 0) {
this.x = this.radius;
this.vx = -this.vx;
}
// Right wall
if (this.x + this.radius > WIDTH) {
this.x = WIDTH - this.radius;
this.vx = -this.vx;
}
// Top wall
if (this.y - this.radius < 0) {
this.y = this.radius;
this.vy = -this.vy;
}
// Bottom wall
if (this.y + this.radius > HEIGHT) {
this.y = HEIGHT - this.radius;
this.vy = -this.vy;
}
}
}
// Initialize particles with random positions and velocities
const particles = [];
// Helper function to generate random number in range [min, max)
function randomRange(min, max) {
return Math.random() * (max - min) + min;
}
// To avoid initial overlap, we try to place particles with some checks
function isOverlapping(x, y, particles) {
for (let p of particles) {
const dx = p.x - x;
const dy = p.y - y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < PARTICLE_DIAMETER) {
return true;
}
}
return false;
}
for (let i = 0; i < PARTICLE_COUNT; i++) {
let x, y;
let attempts = 0;
do {
x = randomRange(PARTICLE_RADIUS, WIDTH - PARTICLE_RADIUS);
y = randomRange(PARTICLE_RADIUS, HEIGHT - PARTICLE_RADIUS);
attempts++;
if (attempts > 1000) {
// If too many attempts, just accept position to avoid infinite loop
break;
}
} while (isOverlapping(x, y, particles));
// Random velocity magnitude between 1 and 3 pixels per frame
const speed = randomRange(1, 3);
// Random direction angle
const angle = randomRange(0, 2 * Math.PI);
const vx = speed * Math.cos(angle);
const vy = speed * Math.sin(angle);
particles.push(new Particle(x, y, vx, vy));
}
// Collision detection and resolution between two particles
function resolveCollision(p1, p2) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const dist = Math.sqrt(dx * dx + dy * dy);
// Normal vector
const nx = dx / dist;
const ny = dy / dist;
// Tangent vector
const tx = -ny;
const ty = nx;
// Dot product tangent
const dpTan1 = p1.vx * tx + p1.vy * ty;
const dpTan2 = p2.vx * tx + p2.vy * ty;
// Dot product normal
const dpNorm1 = p1.vx * nx + p1.vy * ny;
const dpNorm2 = p2.vx * nx + p2.vy * ny;
// Conservation of momentum in 1D for normal velocities (equal mass)
const m1 = dpNorm2;
const m2 = dpNorm1;
// Update velocities
p1.vx = tx * dpTan1 + nx * m1;
p1.vy = ty * dpTan1 + ny * m1;
p2.vx = tx * dpTan2 + nx * m2;
p2.vy = ty * dpTan2 + ny * m2;
// Separate overlapping particles
const overlap = PARTICLE_DIAMETER - dist;
const correctionX = nx * overlap / 2;
const correctionY = ny * overlap / 2;
p1.x -= correctionX;
p1.y -= correctionY;
p2.x += correctionX;
p2.y += correctionY;
}
// Main animation loop
function animate() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
// Update positions
for (let p of particles) {
p.update();
p.checkWallCollision();
}
// Check collisions between particles
for (let i = 0; i < PARTICLE_COUNT; i++) {
for (let j = i + 1; j < PARTICLE_COUNT; j++) {
const p1 = particles[i];
const p2 = particles[j];
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < PARTICLE_DIAMETER) {
resolveCollision(p1, p2);
}
}
}
// Draw particles
for (let p of particles) {
p.draw(ctx);
}
requestAnimationFrame(animate);
}
animate();
})();
</script>
</body>
</html>
How to use:
- Save the above code as
particles.html.
- Open it in any modern web browser.
- You will see 100 blue particles bouncing around inside a white square container.
Explanation:
- Each particle is an instance of the
Particle class with position (x,y), velocity (vx, vy), radius, and mass.
- Particles are initialized with random positions ensuring no initial overlap.
- Velocities are random in direction and magnitude.
- Wall collisions invert the velocity component perpendicular to the wall.
- Particle-particle collisions are resolved using 2D elastic collision physics for equal masses.
- Overlapping particles are separated after collision to prevent sticking.
- The animation runs smoothly using
requestAnimationFrame.
If you want me to help you implement this in another language or add features like trails, gravity, or user interaction, just ask!