4 States of Matter Simulation Using HTML5 Canvas
In this tutorial, we'll explore a simple simulation of the four states of matter—solid, liquid, gas, and plasma—using HTML, CSS, and JavaScript. This interactive demo will help you visualize the behavior of particles in different states.
Demo:
[Embed the live demo or screenshot here]
HTML, CSS, and JavaScript Code:
You can use the following code to create your own 4 states of matter simulation. Simply copy and paste it into your HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>4 States of Matter Simulation</title>
<style>
canvas {
background-color: #f0f0f0;
display: block;
margin: 0 auto;
}
.controls {
text-align: center;
margin: 20px;
}
button {
padding: 10px 20px;
font-size: 16px;
margin: 0 10px;
}
</style>
</head>
<body>
<div class="controls">
<button onclick="setState('solid')">Solid</button>
<button onclick="setState('liquid')">Liquid</button>
<button onclick="setState('gas')">Gas</button>
<button onclick="setState('plasma')">Plasma</button>
</div>
<canvas id="canvas" width="800" height="400"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let particles = [];
let currentState = 'solid';
// Initialize particles
for (let i = 0; i < 100; i++) {
particles.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
vx: 0,
vy: 0,
radius: 5,
});
}
function setState(state) {
currentState = state;
updateParticles();
}
function updateParticles() {
particles.forEach(p => {
if (currentState === 'solid') {
p.vx = 0;
p.vy = 0;
p.x = Math.random() * (canvas.width / 2) + canvas.width / 4;
p.y = Math.random() * (canvas.height / 2) + canvas.height / 4;
} else if (currentState === 'liquid') {
p.vx = (Math.random() - 0.5) * 1;
p.vy = (Math.random() - 0.5) * 1;
} else if (currentState === 'gas') {
p.vx = (Math.random() - 0.5) * 5;
p.vy = (Math.random() - 0.5) * 5;
} else if (currentState === 'plasma') {
p.vx = (Math.random() - 0.5) * 10;
p.vy = (Math.random() - 0.5) * 10;
}
});
}
function drawParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach(p => {
p.x += p.vx;
p.y += p.vy;
if (p.x < 0 || p.x > canvas.width) p.vx = -p.vx;
if (p.y < 0 || p.y > canvas.height) p.vy = -p.vy;
ctx.beginPath();
ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
ctx.fillStyle = currentState === 'plasma' ? 'orange' : 'blue';
ctx.fill();
});
}
function animate() {
drawParticles();
requestAnimationFrame(animate);
}
// Start the animation loop
animate();
</script>
</body>
</html>