前端每日實戰:127# 視頻演示如何用純 CSS 創做一個圓環旋轉錯覺動畫

圖片描述

效果預覽

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

https://codepen.io/comehope/pen/oPWJNj/html

可交互視頻

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

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

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

源代碼下載

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

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

代碼解讀

定義 dom,容器中包含 10 個 <div> 子元素,每一個 <div> 子元素內還有一個 <span> 子元素:函數

<figure class="container">
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
    <div><span></span></div>
</figure>

定義容器尺寸:flex

.container {
    width: 17em;
    height: 17em;
    font-size: 16px;
}

定義子元素的尺寸,和容器相同:動畫

.container {
    position: relative;
}

.container div {
    position: absolute;
    width: inherit;
    height: inherit;
}

在子元素的正中畫一個黃色的小方塊:

.container div {
    display: flex;
    align-items: center;
    justify-content: center;
}

.container span {
    position: absolute;
    width: 1em;
    height: 1em;
    background-color: yellow;
}

增長讓小方塊左右移動的動畫效果,動畫時長還會在後面用到,因此定義成變量:

.container span {
    --duration: 2s;
    animation: move var(--duration) infinite;
}

@keyframes move {
    0%, 100% {
        left: calc(10% - 0.5em);
    }

    50% {
        left: calc(90% - 0.5em);
    }
}

貝賽爾曲線調整動畫的時間函數,使小方塊看起來就像在左右兩側跳來跳去:

.container span {
    animation: move var(--duration) cubic-bezier(0.6, -0.3, 0.7, 0) infinite;
}

增長小方塊變形的動畫,使它看起來有下蹲起跳的擬人效果:

.container span {
    animation: 
        move var(--duration) cubic-bezier(0.6, -0.3, 0.7, 0) infinite,
        morph var(--duration) ease-in-out infinite;
}

@keyframes morph {
    0%, 50%, 100% {
        transform: scale(0.75, 1);
    }

    25%, 75% {
        transform: scale(1.5, 0.5);
    }
}

至此,完成了 1 個方塊的動畫。接下來設置多個方塊的動畫效果。

爲子元素定義 CSS 下標變量:

.container div:nth-child(1) { --n: 1; }
.container div:nth-child(2) { --n: 2; }
.container div:nth-child(3) { --n: 3; }
.container div:nth-child(4) { --n: 4; }
.container div:nth-child(5) { --n: 5; }
.container div:nth-child(6) { --n: 6; }
.container div:nth-child(7) { --n: 7; }
.container div:nth-child(8) { --n: 8; }
.container div:nth-child(9) { --n: 9; }

旋轉子元素,使小方塊分佈均勻地在容器的四周,圍合成一個圓形:

.container div {
    transform: rotate(calc(var(--n) * 40deg));
}

設置動畫延時,如今看起來就像是一羣小方塊貼着一個圓的內邊線在旋轉了(但實際上沒有任何元素在作旋轉運動,大腦感受到的旋轉是一種錯覺):

.container span {
    animation-delay: calc(var(--duration) / 9 * var(--n) * -1);
}

最後,爲小方塊上色:

.container span {
    background-color: hsl(calc(var(--n) * 80deg), 100%, 70%);
}

大功告成!

相關文章
相關標籤/搜索