iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0
Modern Web

CSS 讓你的網頁動起來系列 第 19

CSS微動畫 - 倒數計時,繪製圓餅圖!

Q: 這個用Svg做吧?
A: 如果你的需求跟我這款一樣,Css就可以畫囉~

上一篇的時鐘給小編這一篇的靈感!倒數計時的圓餅圖自己做~網路上很多svg的範本,本篇以animation做出圓餅圖的效果!!

樣式先出來

本篇要畫的只有一個圓!至於半圓的效果,以父層 border-radius: 50%搭配overflow: hidden,這樣子層的元素就算是方形的,也會因為父層的overflow: hidden被遮住。

<style>
  .container {
    position: relative;
    display: inline-block;
    width: 300px;
    height: 300px;
    background-color: BlanchedAlmond;
    border-radius: 50%;
    overflow: hidden;
  }
  .half-round {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 50%;
    transform-origin: bottom;
    background: MediumTurquoise;
  }
</style>

<div class="container">
  <div class="half-round first"></div>
  <div class="half-round second"></div>
</div>

countdown style countdown overflow

旋轉半圓

將第一個半圓負的旋轉90deg,第二個半圓正的旋轉90deg,即可填滿整個圓。

<style>
  .first {
    transform: rotate(-90deg);
  }
  .second {
    transform: rotate(90deg);
  }
</style>

countdown full

動畫效果來了!!

  • 兩個半圓的相同設定為:
    • animation-duration皆設置為10秒。
    • animation-fill-mode皆設置為forwards,這樣動畫演繹結束後,元素的樣式會停留在動畫的最後一個樣子。
<style>
  .half-round {
    animation-duration: 10s;
    animation-fill-mode: forwards;
  }
</style>
  • 第一個圓的動畫設定為:
    • 動畫的設定分為兩部分。
    • animation-timing-function設置為steps(1, start)。由於這個值的設定,動畫看起來就會跟之前認知到的animation效果看起來比較不一樣!之後會有篇章特別說明。
<style>
  .first {
    animation-name: roundFirst;
    animation-timing-function: steps(1, start);
  }
  @keyframes roundFirst {
    0%, 50% {
      background: MediumTurquoise;
      left: 0;
      z-index: 0;
    }
    100% {
      background-color: BlanchedAlmond;
      left: 50%;
      z-index: 1;
    }
  }
</style>

countdown first 50% countdown first 100%

前半段時間會顯示第一張圖的樣式,後半段時間會顯示第二張圖樣式
Mov轉換Gif一直失敗,無法顯示正確的動畫效果,以文字說明


  • 第二個圓的動畫設定就是流暢地繞一圈。
<style>
  .second {
    animation-timing-function: linear;
    animation-name: roundSecond;
  }
  @keyframes roundSecond {
    0% {
      transform: rotate(90deg);
    }
    100% {
      transform: rotate(450deg);
    }
  }
</style>

countdown second

兩個半圓結合在一起

其實到目前為止,希望的效果已經做完了!!如果想要再多一點變化,加上文字或是中間再遮上一個圓讓倒數看起來是邊框在倒數。本篇的例子不用svg,而是使用比較特別的animation-timing-functionsteps,下一篇為大家特別說明囉!
countdown both


如果有寫錯的地方,歡迎點評! 會及時改進~
如果有更好的寫法,歡迎指教! 希望各位不吝賜教~
如果想看更多效果,歡迎敲碗! 提供示意圖小編寫寫看~
如果內容疑似侵權,拜託告知! 內容皆為小編理解後原創~
如果對你有點幫助,拿去用吧!


上一篇
CSS微動畫 - Slot的變化!數字鐘也可以動起來
下一篇
CSS微動畫 - 動起來番外篇!談談Animation的Step
系列文
CSS 讓你的網頁動起來30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言