summaryrefslogtreecommitdiff
path: root/stars.js
blob: cb823ac7481c1a93ad59daa7543745efd2f76017 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function animate() {
    const bg = document.querySelector("#bg");

    for (const star of bg.children) {
        star.x += star.vx;
        star.y += star.vy;
        
        star.style.left = `${star.x}px`;
        star.style.top = `${star.y}px`;
    }
    
    requestAnimationFrame(animate);
}

document.addEventListener("DOMContentLoaded", () => {
    const bg = document.createElement("div");
    bg.setAttribute("id", "bg");

    const numStars = Math.floor((window.innerWidth * window.innerHeight)/10_000);
    for (let i = 0; i < numStars; i++) {
        const star = document.createElement("div");
        star.classList.add("star");
        
        star.x = Math.random() * window.innerWidth;
        star.y = Math.random() * window.innerHeight;
        
        star.vx = (Math.random() - 0.5) * 0.2;
        star.vy = (Math.random() - 0.5) * 0.2;
        
        star.style.left = `${star.x}px`;
        star.style.top = `${star.y}px`;
        
        bg.appendChild(star);
    }
    document.body.prepend(bg);

    var styleBlock = document.createElement("style");
    styleBlock.textContent = `
        #bg {
            position: fixed;
            inset: 0;
            pointer-events: none;
            z-index: 0;
        }

        .star {
            position: absolute;
            width: 3px;
            height: 3px;
            border-radius: 50%;
            background: #e6e6e6;
            box-shadow: 0 0 4px white;
        }
    `;
    document.head.append(styleBlock);

    requestAnimationFrame(animate);
})