[CSS100] Day 10 Watch
Cathy P

Watch Demo

See the Pen 100DaysCss #10 by Cathy (@smile25896) on CodePen.

繼上一次[CSS100] Day 05 Statistic用過 SVG 之後,這次不停繞圈圈的圓也要用到 SVG。另外繞圈圈的效果還新學到了stroke-dasharraystroke-dashoffset這兩個屬性。

學習重點

  1. 用 svg 製作一個空心的圓
  2. 製作繞圈的效果:stroke-dasharraystroke-dashoffset

用 svg 製作一個空心的圓

html 部分,使用了 svg 中的circlecxcy分別代表圓心 x 軸與 y 軸的位置,r則代表了圓的半徑。
因此可以透過下面的 html,畫出一個圓

1
2
3
<svg class="spinner" viewBox="0 0 202 202" xlmns="https://www.w3.org/2000/svg">
<circle cx="101" cy="101" r="99.5"></circle>
</svg>

接著要透過 css 將這個圓調整成空心的圓:

1
2
3
4
5
circle {
stroke: #f85b5b; // 邊框顏色
stroke-width: 3; // 邊框寬度
fill: none; // 填充顏色:無
}

詳細的 SVG 教學,我覺得可以參考ooxx 的教學介紹得相當詳盡。

製作繞圈的效果(stroke-dasharray 和 stroke-dashoffset)

stroke-dasharray

是用來畫虛線的屬性,可以讓stroke一段實線一段空白一段實線一段空白的效果。
直接用 MDN 上的範例來說明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<svg viewBox="0 0 30 10" xmlns="http://www.w3.org/2000/svg">
<!-- 沒有虛線 -->
<line x1="0" y1="1" x2="30" y2="1" stroke="black" />

<!-- 線段和空白的長度相同 -->
<line x1="0" y1="3" x2="30" y2="3" stroke="black" stroke-dasharray="4" />

<!-- 線段長度4,空白長度1 -->
<line x1="0" y1="5" x2="30" y2="5" stroke="black" stroke-dasharray="4 1" />

<!-- 若設定奇數:線段4 空白1 線段2 空白4 線段1 空白2不斷循環 -->
<line x1="0" y1="7" x2="30" y2="7" stroke="black" stroke-dasharray="4 1 2" />

<!-- 若設定偶數線段和空白的長度就會是固定的 -->
<line
x1="0"
y1="9"
x2="30"
y2="9"
stroke="black"
stroke-dasharray="4 1 2 3"
/>
</svg>

呈現的效果:

stroke-dashoffset

可以將用stroke-dasharray畫出的虛線向後推移。

製作繞圈的效果

認識完上面兩個屬性,只要將stroke-dasharray的長度設超過圓的周長,再控制stroke-dashoffset將他推移,就能完成繞圈的效果。