const canvas = document.getElementById('particleCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let particles = [];
const MAX_LEN = 200;
function limitParticlesInView(maxParticles) {
const particlesInView = particles.filter((particle) => {
return particle.x > 0 && particle.x < canvas.width && particle.y > 0 && particle.y < canvas.height;
});
if (particlesInView.length > maxParticles) {
particles.splice(maxParticles, particlesInView.length - maxParticles);
}
}
class Particle {
constructor(x, y, radius, color, speedX, speedY) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.speedX = speedX;
this.speedY = speedY;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
update() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function randomIntFromRange(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function randomColor(colors) {
return colors[Math.floor(Math.random() * colors.length)];
}
function init() {
for (let i = 0; i < 100; i++) {
const radius = randomIntFromRange(1, 5);
const x = randomIntFromRange(radius, canvas.width - radius);
const y = randomIntFromRange(radius, canvas.height - radius);
const color = randomColor(['#f44336', '#3f51b5', '#4caf50', '#ffeb3b', '#ff5722']);
const speedX = (Math.random() - 0.5) * 2;
const speedY = (Math.random() - 0.5) * 2;
particles.push(new Particle(x, y, radius, color, speedX, speedY));
}
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles.forEach((particle) => {
particle.update();
particle.draw();
});
limitParticlesInView(MAX_LEN);
}
canvas.addEventListener('click', (event) => {
const x = event.clientX;
const y = event.clientY;
for (let i = 0; i < 10; i++) {
const radius = randomIntFromRange(3, 6);
const color = randomColor(['#f44336', '#3f51b5', '#4caf50', '#ffeb3b', '#ff5722']);
const speedX = (Math.random() - 0.5) * 4;
const speedY = (Math.random() - 0.5) * 4;
particles.push(new Particle(x, y, radius, color, speedX, speedY));
}
});
init();
animate();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
init();
});
<canvas id="particleCanvas"></canvas>
canvas {
display: block;
position: absolute;
top: 0;
left: 0;
}