用 svg 畫圓

用 svg 畫圓

使用 SVG 須要在最外層包含<svg></svg>。css

  1. SVG 中基本的形狀(basis shape)有 circle、ellipse、line、ploygon、polyline、rect,環形的展現在這裏使用的是 circle;

基礎圓形

image.png

html { font-size: 16px;} 
body { font-family: sans-serif; }

.contain {
  display: flex;
  justify-content: center;
  padding: .65rem;
  box-sizing: border-box;
}
<div class="contain">
  <svg width="200px" height="200px" viewBox="0 0 200 200">
    <circle class="path" 
            stroke="hotpink" 
            fill="none" 
            stroke-width="5" 
            cx="100" cy="100" r="80" />
  </svg>
</div>
  1. SVG 元素使用 width, height 來定義自身在頁面上的 viewport,配合 viewbox 屬性,來對內部子元素的單位進行計算。width、height 表明 SVG 的大小。
  2. ViewBox 的四個值也是用來設置自身大小的,至關於在 SVG 上鋪了一層布,而後在這個布上畫東西,這個布的大小隨便你定,只要它超過了 SVG 的大小,那麼就會被默認總體縮小。也能夠不設置 viewBox,那麼若是你的 circle 若是大小正好超過了 SVG 的大小,就會被剪切掉。
  3. Fill 屬性是指圓環中興部分填充的顏色,這裏設置的是 nonestroke 是指圓環描邊的填充顏色,配合 stroke-width 來設置描邊的寬度。
  4. cx、cy 表示圓心部分的座標,r 表明圓的半徑。

描邊點狀化

image.png

<circle class="path" 
            stroke="hotpink" 
            fill="none" 
            stroke-width="5" 
            stroke-dasharray="10"
            cx="100" cy="100" r="80" />
<circle class="path" 
            stroke="hotpink" 
            fill="none" 
            stroke-width="5" 
            stroke-dasharray="50"
            cx="100" cy="100" r="80" />
<circle class="path" 
            stroke="hotpink" 
            fill="none" 
            stroke-width="5" 
            stroke-dasharray="100"
            cx="100" cy="100" r="80" />
  1. stroke-dasharray 屬性,能夠將圖形的描邊進行「點狀化」,這裏須要理解的是,「點狀化」的「點」,其大小是能夠設置的,並不真的就是那麼一個「·」,能夠變長或者變短。上面例子中的三個 circle 分別設置 stroke-dasharray 爲 10,50,100;
  2. 因此若是 circle 的點的長度正好等於 circle 邊長,那麼「點」看上去就是 circle 的邊。
  3. 須要注意的是,由於通常都設置了顏色,因此點與點之間的的空白可能不會引發注意,其實它也是一個點,只不過是透明的,長度仍然和其餘同樣。

動起來

常常能夠看到一些圓形進度條,能夠徹底使用 css 實現,可是比較複雜,使用 SVG 比較簡單。
codeOpenhtml

  1. stroke-dashoffset 可使上一步中使用 stroke-dasharray 生成的「點」沿着 path 移動,默認狀況下,若是是圓形,那麼是逆時針移動;
  2. 將前面的 circle 的 stroke-dasharray 長度設置爲它的周長。設置它的 stroke-dashoffset 爲它的周長,因此它會逆時針移動一個周長,可是因爲前面的 stroke-dasharray 也設置的是一個周長,因此當逆時針移動後,stoke-dasharray 設置的點的空白部分會填充這個圓。像前面那樣調整了以後,初始狀態看起來就像是進度爲 0 的進度條。以後經過改變 stroke-dasharray 的值來使 前面提到的點動起來, 來達到起來是一個在運動的進度條的效果, 或者使用下面的方式。
  3. circle 描邊的「起始位置」在 circle 在 x 軸方向,使用 transform: rotate() 逆時針旋轉 90 度使「起始位置」定位到 12 點方向。
相關文章
相關標籤/搜索