JavaScript Background Stars

Create Background Stars Animation vanilla javascript

html

<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./main.js" defer></script>
    <title>Stars Effect</title>
</head>

<body>
</body>

</html>

css

body {
            margin: 0;
            overflow: hidden;
            background-color: #000000;
        }

        .star {
            position: absolute;
            border-radius: 50%;
            pointer-events: none;
            background-color: #ffffffcc;
            box-shadow: 0 0 10px #ffffffcc;
        }

javascript

function starFunc() {
    const star = document.createElement('div');
    star.classList.add('star');
    document.body.appendChild(star);

    const startX = Math.random() * window.innerWidth;
    const startY = Math.random() * window.innerHeight;

    const size = Math.random() * 3 + 2;
    const duration = Math.random() * 1 + 0.5;

    star.style.width = `${size}px`;
    star.style.height = `${size}px`;
    star.style.position = 'absolute';
    star.style.top = `${startY}px`;
    star.style.left = `${startX}px`;
    star.style.borderRadius = '50%';
    star.style.backgroundColor = `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 1)`;
    star.style.transition = `transform ${duration}s ease-in-out, opacity ${duration}s ease-in-out`;

    setTimeout(() => {
        star.style.transform = `translate(${Math.random() * window.innerWidth - startX}px, -1000px)`;
        star.style.opacity = '0';
    }, 10);

    setTimeout(() => {
        star.remove();
    }, duration * 1000);
}

setInterval(() => {
    starFunc();
}, 10);