如何使用純CSS實現一個轉動的單車車輪的動畫效果

來源:互聯網
上載者:User
本篇文章給大家帶來的內容是關於如何使用純CSS實現一個轉動的單車車輪的動畫效果 ,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

效果預覽

原始碼下載

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

代碼解讀

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

<div class="wheel">    <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-image: linear-gradient(#555, #222);}

畫出輪圈:

.wheel {    width: 9em;    height: 9em;    font-size: 25px;    border: 0.4em solid #777;    border-radius: 50%;    box-shadow: 0 0 0 0.5em #111;}

定義輻條的樣式:

.wheel {    display: flex;    align-items: center;    justify-content: center;}.wheel span {    position: absolute;    width: 8em;    height: 1em;    border: 0.1em solid;    border-color: #ccc transparent;}

定義變數,畫出多根幅條:

.wheel span {    transform: rotate(calc((var(--n) - 1) * 30deg));}.wheel span:nth-child(1) {    --n: 1;}.wheel span:nth-child(2) {    --n: 2;}.wheel span:nth-child(3) {    --n: 3;}.wheel span:nth-child(4) {    --n: 4;}.wheel span:nth-child(5) {    --n: 5;}.wheel span:nth-child(6) {    --n: 6;}

讓車輪轉動起來:

.wheel span {    animation: run 4s linear infinite;}@keyframes run {    to {        transform: rotate(calc((var(--n) - 1) * 30deg + 360deg));    }}

用虛擬元素畫出地面上的線條:

.wheel {    position: relative;}.wheel::before {    content: '';    position: absolute;    width: 15em;    height: 0.2em;    top: 11em;    background-image: linear-gradient(            to right,            silver 0, silver 4em,            transparent 4em, transparent 5em,            silver 5em, silver 10em,            transparent 10em, transparent 12em,            silver 12em, silver 14em,            transparent 14em, transparent 15em        );}

最後,讓地面上的線條動起來,形成車輪向前走的效果:

.wheel::before {    background-position: 15em;    animation: run2 6s linear infinite;}@keyframes run2 {    to {        background-position: -15em;    }}

大功告成!

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.