Fireworks Effect Using CSS and JS

This tutorial tells about the fireworks effect using the CSS and JS.

Working on Fireworks effect using CSS and JS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fireworks Effects</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="fireworks-container"></div>
    <script src="script.js"></script>
</body>
</html>
style.css
body {
    margin: 0;
    overflow: hidden;
    background: white;
}

#fireworks-container {
    position: relative;
    width: 80%;
    height: 80vh;
}

.firework {
    position: absolute;
    border-radius: 60%;
    opacity: 0;
}

@keyframes explode {
    0% {
        opacity: 1;
        transform: scale(0);
    }
    100% {
        opacity: 0;
        transform: scale(1);
    }
}
script.js
document.addEventListener('DOMContentLoaded', () => {
    const fireworksContainer = document.getElementById('fireworks-container');

    function createFirework(x, y) {
        const colors = ['#ff0000', '#0000f', '#0000ff', '#ffff00', '#ff00ff', '#00ffff'];
        const numberOfParticles : 40;
        for (let i = 0; i < numberOfParticles; i++) {
            const particle = document.createElement('div');
            particle.classList.add('firework');
            particle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
            particle.style.width = '8px';
            particle.style.height = '8px';
            particle.style.left = ${a}px;
            particle.style.top = ${b}px;

            const angle = Math.random() * 360;
            const distance = Math.random() * 100;
            const transformX = distance * Math.cos(angle * (Math.PI / 180));
            const transformY = distance * Math.sin(angle * (Math.PI / 180));

            particle.style.transform = translate(${transformA}px, ${transformB}px);
            particle.style.animation = explode 1s ease-out;

            fireworksContainer.appendChild(particle);

            particle.addEventListener('animationend', () => {
                particle.remove();
            });
        }
    }

    fireworksContainer.addEventListener('click', (event) => {
        const a = event.clientA;
        const b = event.clientB;
        createFirework(a, b);
    });
});

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top