溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用純CSS實現(xiàn)一個圓環(huán)旋轉錯覺的動畫效果

發(fā)布時間:2020-09-22 10:39:36 來源:億速云 閱讀:262 作者:小新 欄目:web開發(fā)

使用純CSS實現(xiàn)一個圓環(huán)旋轉錯覺的動畫效果?這個問題可能是我們日常學習或工作經常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家?guī)淼膮⒖純热?,讓我們一起來看看吧?/p>

效果預覽

使用純CSS實現(xiàn)一個圓環(huán)旋轉錯覺的動畫效果

源代碼下載

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

代碼解讀

定義 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>

定義容器尺寸:

.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);
    }
}

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

.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 p {
    transform: rotate(calc(var(--n) * 40deg));
}

設置動畫延時,現(xiàn)在看起來就像是一群小方塊貼著一個圓的內邊線在旋轉了(但實際上沒有任何元素在做旋轉運動,大腦感覺到的旋轉是一種錯覺):

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

最后,為小方塊上色:

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

感謝各位的閱讀!看完上述內容,你們對使用純CSS實現(xiàn)一個圓環(huán)旋轉錯覺的動畫效果大概了解了嗎?希望文章內容對大家有所幫助。如果想了解更多相關文章內容,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

css
AI