iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 19
0
Modern Web

CSS Secrets 導讀系列 第 19

Secret 14: 簡單的圓餅圖 (SVG)

SVG讓許多圖像的工作變簡單,製作圓餅圖也不例外。然而與其用路徑畫圓餅圖,我們要用一個小技巧。

先從一個圓形開始:

<svg width="100" height="100">
<circle r="30" cx="50" cy="50" />
</svg>

https://ithelp.ithome.com.tw/upload/images/20181103/20091606tETYUGGTLE.png

然後加上一些基本的樣式:

circle {
	fill: yellowgreen;
	stroke: #655;
	stroke-width: 30;
}

https://ithelp.ithome.com.tw/upload/images/20181103/20091606XYPlQE035y.png

這是我們用30單位的邊框畫的圓,SVG的stroke等同border,除了stroke-width之外還有一些較不為人知的屬性可以用來微調邊框。其中一個是stroke-dasharray,用來做出虛線的邊框。

stroke-dasharray: 20 10;

https://ithelp.ithome.com.tw/upload/images/20181103/20091606yvADW2nuaJ.png

這表示我們要做出長20間隔10的邊框。到這裡你或許會問,虛線的邊框跟圓餅圖有什麼關係?注意看,當我們將邊框虛線長度設0間隔設成大於或等於圓週的時候,邊框就不見了,只剩下綠色的圓形。有趣的是當我們增加第一個值,因為間隔實在太大了,在圓週的範圍內不會再有另一個邊框,只會有一個虛線邊框,它覆蓋的範圍就是我們指定的值。

/* 
	圓週 = 2 * 半徑 * 圓週率π
	2 * 30 * 3.14 = 189
*/
stroke-dasharray: 0 189;

https://ithelp.ithome.com.tw/upload/images/20181103/20091606MAtQQu1zL9.png
(從左到右,stroke-dasharray值分別為 0, 40, 95, 150)

或許你已經看出來我們的意圖,如果我們減少圓形的半徑讓它完全被邊框覆蓋,就會得到一個和圓餅圖很像的圖案。因為SVG的邊框一定會有一半在圖形內,一半在圖形外,當圓形半徑是邊框值一半的時候,中間的空心就會被填滿。

<svg width="100" height="100">
<circle r="25" cx="50" cy="50" />
</svg>
circle {
	fill: yellowgreen;
	stroke: #655;
	stroke-width: 50;
	stroke-dasharray: 60 158; /* 2π x 25 = 158 */
}

https://ithelp.ithome.com.tw/upload/images/20181103/20091606ypGQ2AEMad.png

最後我們只要將SVG逆時鐘轉90度,再製作一個和邊框同寬的圓底在最底下,我們的圓餅圖就大功告成了。

svg {
	transform: rotate(-90deg);
	background: yellowgreen;
	border-radius: 50%;
}

https://ithelp.ithome.com.tw/upload/images/20181103/20091606fqO6yeSvjw.png

這個方法也讓我們能輕易的為圓餅圖加上動態效果。

@keyframes fillup {
  to { stroke-dasharray: 158 158; }
}

circle {
    fill: yellowgreen;
	stroke: #655;
	stroke-width: 50;
    stroke-dasharray: 60 158;
    animation: fillup 5s linear infinite;
}

CodePen


上一篇
Secret 14: 簡單的圓餅圖 (CSS transforms)
下一篇
Secret 15: 單邊陰影
系列文
CSS Secrets 導讀30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言