1. 程式人生 > >如何用純 CSS 創作一個變色旋轉動畫

如何用純 CSS 創作一個變色旋轉動畫

效果預覽

線上演示

按下右側的“點選預覽”按鈕可以在當前頁面預覽,點選連結可以全屏預覽。

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

可互動視訊

此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。

請用 chrome, safari, edge 開啟觀看。

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

原始碼下載

本地下載

每日前端實戰系列的全部原始碼請從 github 下載:


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


程式碼解讀


定義 dom,容器中包含 9 個元素:

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

居中顯示:

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: black;
}

定義容器尺寸:

.container {
    width: 30em;
    height: 30em;
    font-size: 12px;
}

設定容器中線條的樣式:

.container {
    color: lime;
}

.container span {
    position: absolute;
    width: 5em;
    height: 5em;
    border-style: solid;
    border-width: 1em 1em 0 0;
    border-color: currentColor transparent;
    border-radius: 50%;
}

讓線條在容器中居中顯示:

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

定義變數,使線條從中心向外側逐漸延伸:

.container span {
    --diameter: calc(5em + (var(--n) - 1) * 3em);
    width: var(--diameter);
    height: var(--diameter);
}

.container span:nth-child(1) {
    --n: 1;
}

.container span:nth-child(2) {
    --n: 2;
}

.container span:nth-child(3) {
    --n: 3;
}

.container span:nth-child(4) {
    --n: 4;
}

.container span:nth-child(5) {
    --n: 5;
}

.container span:nth-child(6) {
    --n: 6;
}

.container span:nth-child(7) {
    --n: 7;
}

.container span:nth-child(8) {
    --n: 8;
}

.container span:nth-child(9) {
    --n: 9;
}

設定讓線條旋轉的動畫效果:

.container span {
    animation: rotating linear infinite;
    animation-duration: calc(5s / (9 - var(--n) + 1));
}

@keyframes rotating {
    to {
        transform: rotate(1turn);
    }
}

定義改變顏色的動畫效果,以色相環一週 360 度為 100%,--percent 變數是指位於這個 100% 的哪個位置:

@keyframes change-color {
    0%, 100% {
        --percent: 0;
    }

    10% {
        --percent: 10;
    }

    20% {
        --percent: 20;
    }

    30% {
        --percent: 30;
    }

    40% {
        --percent: 40;
    }

    50% {
        --percent: 50;
    }

    60% {
        --percent: 60;
    }

    70% {
        --percent: 70;
    }

    80% {
        --percent: 80;
    }

    90% {
        --percent: 90;
    }
}

最後,把改變顏色的動畫效果應用到容器上:

.container {
    --deg: calc(var(--percent) / 100 * 360deg);
    color: hsl(var(--deg), 100%, 50%);
    animation: change-color 5s linear infinite;
}

大功告成!

原文地址:https://segmentfault.com/a/1190000015655171