자바스크립트 예제

[노마드코더] snowflake

자무카 2022. 12. 30.

목차

    노마드 코더 짱이야. 노마드 코더 강의는 참으로 잘 짜여져있어. 그냥 대충 라이브로 떼우는 강의들과 비교하면 기분 상할꺼임.

    노마드 코더 만세.

    body {
        background-color: black;
    }
    .snowflake {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: white;
        animation: fall 10s linear; 
         /* name-duration-linear일정속도 */
         /* Math.random() * 20+최소_동작시간으로 */
        position: absolute;
        top : 1px;
    
    }
    
    @keyframes fall {
        from {}
        to {
            transform: translateY(100vh);
            opacity: 0; /*0~1*/
        }
    }

    // style 속성
    // 1) left x 축 랜덤 ( window.screen.width )
    // 2) animationDelay 낙하 랜덤 구현
    // 3) 눈의 처음 투명도 랜덤 : opacity : Math.random()
    // 4) 낙하 속도 다르게 : style.animation = `fall ${duration}s linear`;
        Math.random() * 20 + 최소_동작시간 <-- 바로 뚝 떨어지면 안되니까.
    // 5) 애니메이션 끝난 후, 태그 지우기 setTimeout , removeChild

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <link rel="stylesheet" href="snowflake.css">
    </head>
    <body>
        <!-- <div class="snowflake"></div> -->
    
        <script>
            const body = document.querySelector("body");
            const MIN_DURATION = 10;
    
            function makeSnowflake() {
                const snowflake = document.createElement("div");
                const delay = Math.random()*5; // delay : 몇 초 후 실행
                const initialOpacity = Math.random(); // opacity 는 0~1 사이값이므로 * X
                const duration = Math.random() * 3 + MIN_DURATION;
    
                snowflake.classList.add("snowflake");
                // snowflake.style.left = "300px";
                snowflake.style.left = `${window.screen.width * Math.random()}px`;
                // snowflake.style.left = `${Math.random() * window.screen.width}px`;
                snowflake.style.animationDelay = `${delay}s`; // {delay}s
                snowflake.style.opacity = initialOpacity;
                snowflake.style.animation = `fall ${duration}s linear`;
    
                body.appendChild(snowflake);   
                // 애니메이션 종료(duration+delay)*1000 으로 종료 후 제거.
                setTimeout(() => {
                    body.removeChild(snowflake);
                }, (duration + delay) * 1000);
            }
            // makeSnowflake();
    		const button = document.querySelector("button");
            button.addEventListener("click", ()=>{
                for (let i=0;i<50;i++){
                    setTimeout(makeSnow, i*500 )
                }
    })
        </script>
    </body>
    </html>

    댓글