本次案例主要使用了svg的三個元素,分別爲circle
、text
、path
,關於svg的介紹你們能夠看MDN上的相關教程,傳送門javascript
因爲svg能夠寫到HTML中,因此這裏咱們就能夠很方便的作進度條加載動畫啦,此次案例以vue來作數據交互html
viewBox屬性定義了畫布上能夠顯示的區域,viewBox有4個值,值1爲svg窗口起點顯示的x座標,值2位svg窗口起點的y座標, 後面的兩個分別爲顯示的大小; 日常能夠經過後面這兩個值對svg圖形進行放大和縮小, 前面的兩個值進行窗口位置的變換vue
在demo中爲了方便計算svg元素的中心,我設置爲(0, 0) 即圓的座標方程知足 x^2 + y^2 = r^2
java
circle元素在svg中能夠畫一個圓,主要屬性爲cx(圓心x座標)、cy(圓心y左邊)、r(圓的半徑)app
svg中顯示字體的元素,text-anchor、dominant-baseline分別能夠設置字體的左右、上線對齊方式dom
svg中全部的基本元素均可以經過path路徑畫出來,該元素只有一個屬性d,動畫的效果就是經過不斷改變d的值來達到的;
在這裏只須要掌握d的A命令便可,傳送門svg
效果圖以及代碼字體
<div id="app"> <svg width="100" height="100" viewBox="-50 -50 100 100"> <circle cx="0" cy="0" stroke-width="6" fill="none" stroke="#ddd" :r="r"/> <path :d="d" fill="none" stroke-width="6" stroke="#369"/> <text text-anchor="middle" dominant-baseline="middle">{{ ratio }}%</text> </svg> </div>
new Vue({ el: '#app', data: { ratio: 1, r: 47 }, computed: { d() { const { ratio } = this return this.getD(ratio) } }, methods: { getD(ratio) { if (ratio >= 100) { ratio = 99.999 } const angle = Math.PI / 50 * ratio const r = this.r const x = r * Math.cos(angle) const y = -r * Math.sin(angle) const isBigAngle = Number(ratio > 50) return `M 47 0 A 47 47 0 ${isBigAngle} 0 ${x} ${y}` } }, mounted() { let timer = setInterval(() => { if (this.ratio > 100) { this.ratio = 100 clearInterval(timer) timer = null return } this.ratio += 1 }, 16) } })
ps:第一次寫博客,發現表達能力真的好差;動畫