
The Confetti Party uses the HTML5 Canvas and JavaScript’s requestAnimationFrame API to create a confetti explosion effect that follows your mouse.
This effect provides a fun, interactive element to enhance user engagement. It’s perfect for celebrating special occasions on websites or adding flair to congratulatory web pages.
How to use it:
1. Create a canvas element where the confetti will be rendered:
<canvas id="confettiCanvas"></canvas>
2. Style the canvas with CSS:
#confettiCanvas {
background-color: #222;
position: absolute;
top: 0;
left: 0;
}3. Write the main JavaScript to create the confetti animation:
- The JavaScript Particle class defines the properties of each confetti piece (position, size, color, speed).
- resizeCanvas ensures the canvas adapts to the browser window size.
- createExplosion generates new particles at the mouse position.
- animate clears the canvas, updates each particle’s position and size, redraws them, and removes faded particles.
- Event listeners handle window resizing and mouse movement to trigger confetti bursts.
- setInterval creates continuous confetti explosions at the mouse position.
const canvas = document.getElementById("confettiCanvas");
const ctx = canvas.getContext("2d");
const colors = ["#FF3F8E", "#04C2C9", "#2E55C1", "#F9D423"];
let particles = [];
let mousePos = { x: 0, y: 0 };
class Particle {
constructor(x, y, size, color, speedX, speedY) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.speedX = speedX;
this.speedY = speedY;
}
update() {
this.x += this.speedX;
this.y += this.speedY;
this.size *= 0.98; // Shrink over time
}
draw() {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function createExplosion(x, y) {
const particleCount = 50;
for (let i = 0; i < particleCount; i++) {
const size = Math.random() * 5 + 2;
const color = colors[Math.floor(Math.random() * colors.length)];
const speedX = (Math.random() * 2 - 1) * 2;
const speedY = (Math.random() * 2 - 1) * 2;
particles.push(new Particle(x, y, size, color, speedX, speedY));
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
particles = particles.filter((particle) => {
particle.update();
particle.draw();
return particle.size > 0.5;
});
requestAnimationFrame(animate);
}
function handleMouseMove(event) {
mousePos.x = event.clientX;
mousePos.y = event.clientY;
}
// Initialize
resizeCanvas();
animate();
// Event listeners
window.addEventListener("resize", resizeCanvas);
canvas.addEventListener("mousemove", handleMouseMove);
// Create explosions at intervals
setInterval(() => {
createExplosion(mousePos.x, mousePos.y);
}, 50);4. Personalize the confetti colors by changing the values in the colors array:
const colors = ["#FF3F8E", "#04C2C9", "#2E55C1", "#F9D423"];







