<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Particle System Animation</title>
<style>
body {
margin: 0;
overflow: hidden;
background-color: #111;
}
canvas {
display: block;
}
</style>
</head>
<body>
<canvas id="particleCanvas"></canvas>
<script>
const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
// Resize canvas to fit the screen
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Particle class to represent each particle
class Particle {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = Math.random() * 5 + 2; // Random size between 2 and 7
this.speedX = Math.random() * 6 - 3; // Random horizontal speed
this.speedY = Math.random() * 6 - 3; // Random vertical speed
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`; // Random color
this.life = 0; // Life of the particle
this.maxLife = Math.random() * 100 + 100; // Max life between 100 and 200
}
// Method to update particle position and properties
update() {
this.x += this.speedX;
this.y += this.speedY;
this.life++;
// Fade out by reducing opacity over time
this.opacity = 1 - this.life / this.maxLife;
// If the particle's life ends, reset its position
if (this.life >= this.maxLife) {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.life = 0;
}
}
// Method to draw the particle
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.opacity; // Apply opacity based on life
ctx.fill();
ctx.closePath();
}
}
// Array to hold particles
const particlesArray = [];
// Function to create particles
function createParticles(e) {
const xPos = e.x;
const yPos = e.y;
for (let i = 0; i < 10; i++) {
particlesArray.push(new Particle(xPos, yPos));
}
}
// Event listener to create particles on mouse move
canvas.addEventListener('mousemove', (e) => {
createParticles(e);
});
// Function to animate and update particles
function animateParticles() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
// Update and draw each particle
for (let i = 0; i < particlesArray.length; i++) {
const particle = particlesArray[i];
particle.update();
particle.draw();
}
requestAnimationFrame(animateParticles); // Recursively call the animation function
}
// Start the animation
animateParticles();
</script>
</body>
</html>