Below is a simple example of a falling sand simulation using HTML, JavaScript, and CSS all in one file. This example creates a canvas where sand particles fall from the top to the bottom, interacting with each other and the boundaries of the canvas.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Falling Sand Simulation</title>
<style>
body {
margin: 0;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const sandParticles = [];
const gravity = 0.1;
class SandParticle {
constructor(x, y) {
this.x = x;
this.y = y;
this.vy = 0;
}
update() {
this.vy += gravity;
this.y += this.vy;
if (this.y + 1 > canvas.height) {
this.y = canvas.height - 1;
this.vy = 0;
}
}
draw() {
ctx.fillStyle = 'rgb(153, 76, 0)';
ctx.fillRect(this.x, this.y, 2, 2);
}
}
function createSand() {
for (let i = 0; i < 100; i++) {
const x = Math.random() * canvas.width;
const y = 0;
sandParticles.push(new SandParticle(x, y));
}
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = sandParticles.length - 1; i >= 0; i--) {
const particle = sandParticles[i];
particle.update();
particle.draw();
// Simple collision check with other particles
for (let j = i - 1; j >= 0; j--) {
const other = sandParticles[j];
if (Math.abs(particle.x - other.x) < 2 && Math.abs(particle.y - other.y) < 2) {
// Swap vy to simulate a simple collision
[particle.vy, other.vy] = [other.vy, particle.vy];
}
}
// Remove particles that are at the bottom and not moving
if (particle.y === canvas.height - 1 && particle.vy === 0) {
// For now, just keep them, but you could remove or reset them here
}
}
// Continuously create new sand particles at the top
if (Math.random() < 0.1) {
sandParticles.push(new SandParticle(Math.random() * canvas.width, 0));
}
requestAnimationFrame(update);
}
createSand();
update();
</script>
</body>
</html>
This code snippet does the following:
Creates a canvas element in the HTML body.
Styles the body and canvas with CSS to center the canvas.
Uses JavaScript to create a simple falling sand simulation. Sand particles are represented by small rectangles that fall due to gravity. The simulation includes basic collision detection between particles and prevents them from falling through the bottom of the canvas.
Continuously adds new sand particles at the top of the canvas to keep the simulation running.
You can copy and paste this into a single file (e.g., falling_sand.html) and open it in a web browser to see the simulation in action.