前端每日實戰:36# 視頻演示如何利用 CSS 動畫原理,在頁面上表現日蝕現象

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。css

https://codepen.io/comehope/pen/OELvrKhtml

可交互視頻教程

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。前端

請用 chrome, safari, edge 打開觀看。git

https://scrimba.com/p/pEgDAM/cgnzMAzgithub

源代碼下載

每日前端實戰系列的所有源代碼請從 github 下載:chrome

https://github.com/comehope/front-end-daily-challengesdom

代碼解讀

定義 dom,一個名爲 sky 的容器,其中包含一個 sun 元素和一個 moon 元素:flex

<div class="sky">
    <div class="sun"></div>
    <div class="moon"></div>
</div>

畫出天空:動畫

body {
    margin: 0;
}

.sky {
    width: 100vw;
    height: 100vh;
    background-color: skyblue;
}

畫出太陽:spa

.sky {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

.sun {
    position: absolute;
    width: 50vmin;
    height: 50vmin;
    border-radius: 50%;
    background-color: gold;
}

畫出月亮:

.moon {
    position: absolute;
    width: 50vmin;
    height: 50vmin;
    border-radius: 50%;
    background-color: slategray;
    transform: translateX(-55vmin);
}

定義天空的變化,當日蝕來臨時天空會變黑:

@keyframes animate-sky {
    50% {
        background-color: black;
    }
}

定義太陽的變化,當日蝕來臨時太陽雖會被遮擋,但光暈仍會透出:

@keyframes animate-sun {
    50% {
        box-shadow: 0 0 5em 1em white;
    }
}

定義月亮的動畫,當它運動到和太陽重疊的位置時,由於沒有光,就看不到它的顏色了:

@keyframes animate-moon {
    from {
        transform: translateX(-100vmin);
    }

    50% {
        background-color: black;
    }

    to {
        transform: translateX(100vmin);
    }
}

把動畫應用到元素上:

.sky,
.sun,
.moon {
    animation: 10s linear infinite;
}

.sky {
    animation-name: animate-sky;
}

.sun {
    animation-name: animate-sun;
}

.moon {
    animation-name: animate-moon;
}

最後,隱藏滾動條:

.sky {
    overflow: hidden;
}

大功告成!

相關文章
相關標籤/搜索