Javascript 밤하늘에 별 생성하기 ( for문 사용, code pen 코드 )

Dustin Jung·2025년 3월 18일

웹퍼블리싱 공부

목록 보기
9/20

포폴이 우주 배경이라, 밤하늘에 별을 만들어야 했다.

물론 내가 발상하진 않았고, 이 역시 찾은 것,

내거로 만들기 위해, 헤체 분석 들어간다.

코드 찾은 곳은 codepen

https://codepen.io/harshpreet_singh/details/PoMxGaX

<style>

.stars {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
}
.star {
    position: absolute;
    width: 4px;
    height: 4px;
    background: white;
    border-radius: 50%;
    animation: twinkle var(--twinkle-duration) ease-in-out infinite;
}

@keyframes twinkle {
    0%, 100% {
        opacity: 0.2;
    }
    50% {
        opacity: 1;
    }
}

</style>

<script>

        function createStars() {
            const starsContainer = document.createElement('div');
            starsContainer.className = 'stars';
        
            for (let i = 0; i < 100; i++) {
                const star = document.createElement('div');
                star.className = 'star';
                star.style.left = `${Math.random() * 100}%`;
                star.style.top = `${Math.random() * 100}%`;
                star.style.setProperty('--twinkle-duration', `${1 + Math.random() * 3}s`);
                starsContainer.appendChild(star);
            }
        
            const footer = document.getElementById("sticky-footer"); 
            footer.appendChild(starsContainer); 
        }

</script>

div를 만들고, 그 div에 starsContainer라는 변수를 상수로 부여,
그리고 그 변수의 className을 stars라고 만든다.

그 후, for문을 100번 시행해서, className으로 star을 받은 div, 변수 star을 100개 만든다.

이 star는 각각 Math.random()으로 left, top 을 다르게( 랜덤하게 ) 적용,

star의 style을 javascript로 setProperty를 사용해서 --twinkle duration으로 만들고.

그 값을 랜덤하게 설정한다.

Math.random() → 0 이상 1 미만의 랜덤 숫자 반환
Math.random() 3 → 0 이상 3 미만의 랜덤 숫자 반환
1 + Math.random()
3 → 1 이상 4 미만(즉, 1~3초) 랜덤한 값 생성
뒤에 s를 붙여서 초 단위(1s~4s)로 설정

=> 결과적으로 각 별이 1초에서 4초 사이의 랜덤한 시간 동안 반짝이게 된다.

그 후 그것을 방금 만든 starContainer의 자식요소로 박아 넣는다.

간단하지만 똑똑한 발상- 이런걸 보고 배워야 한다..

profile
더스틴 정입니다

0개의 댓글