svg 圓環進度動畫


簡介

近日業務需要,特來鑽研一陣,最后選型svg技術實現,因為方便。

實現步驟

一、先畫一圓環

<svg xmlns="http://www.w3.org/2000/svg" height="110" width="110" viewBox="0 0 110 110">
    <circle cx="50%" cy="50%" r="50" stroke-width="10" stroke="#F2F2F2" fill="none"></circle>
</svg>

定義讓外層容器為寬高110px的正方形,並且定義在容器的中心處(cx="50%"" cy="50%")畫半徑為50px的圓(r="50"),圓的內容不着色(fill="none")。描邊為10px,着描邊色為灰色(stroke-width="10" stroke="#F2F2F2")

二、再來一層綠色圓環疊加

<svg xmlns="http://www.w3.org/2000/svg" height="110" width="110" viewBox="0 0 110 110">
    <circle cx="50%" cy="50%" r="50" stroke-width="10" stroke="#F2F2F2" fill="none"></circle>
    <circle id="ring" cx="50%" cy="50%" r="50" stroke-width="10" stroke="green" fill="none"
    transform="rotate(-90 55 55)"
    stroke-dasharray="100, 314"></circle>
</svg>

下面的 circle 着描邊為綠,並且寫上了 stroke-dasharray ,此屬性參數第一個數值表示dash,這里代表覆蓋范圍,后一個數字表示gap長度默認為circle的周長314。此外tranform屬性的作用是將圓環從0點位置開始覆蓋,不寫此屬性則從3點位置開始覆蓋(rotate第一個參數為角度,第二個和第三個參數為旋轉中心,這里為容器的中心)。

三、給圓環加入漸變色

<svg xmlns="http://www.w3.org/2000/svg" height="110" width="110" viewBox="0 0 110 110">
    <linearGradient id="svg-gradient" gradientUnits="userSpaceOnUse" x1="100%" y1="100%" x2="0%" y2="0%">
        <stop offset="0%" style="stop-color:yellow"/>
        <stop offset="100%" style="stop-color:green"/>
    </linearGradient>
    <circle cx="50%" cy="50%" r="50" stroke-width="10" stroke="#F2F2F2" fill="none"></circle>
    <circle id="ring" cx="50%" cy="50%" r="50" stroke-width="10" fill="none"
    stroke="url(#svg-gradient)" 
    transform="rotate(-90 55 55)"
    stroke-dasharray="200, 314"></circle>
</svg>

id為ring的 circle 改變了stroke屬性為 url(#svg-gradient) ,意為以上面的 linearGradient 背景,以起點黃到終點綠漸變。

四、加入動畫

<style>
circle {
    -webkit-transition: stroke-dasharray 2s;
    transition: stroke-dasharray 2s;
}
</style>

設置css動畫持續2s

<svg xmlns="http://www.w3.org/2000/svg" height="110" width="110" viewBox="0 0 110 110">
    <linearGradient id="svg-gradient" gradientUnits="userSpaceOnUse" x1="100%" y1="100%" x2="0" y2="0">
        <stop offset="0%" style="stop-color:yellow"/>
        <stop offset="100%" style="stop-color:green"/>
    </linearGradient>
    <circle cx="50%" cy="50%" r="50" stroke-width="10" stroke="#F2F2F2" fill="none"></circle>
    <circle id="ring" cx="50%" cy="50%" r="50" stroke-width="10" fill="none"
    stroke="url(#svg-gradient)" 
    transform="rotate(-90 55 55)"
    stroke-dasharray="0, 314"></circle>
</svg>

id為ring的 circle 改變了 stroke-dasharray 使其 dash 參數初始化為0。

var targetRing = document.getElementById('ring');
var totalLength = targetRing.getTotalLength();

targetRing.style.strokeDasharray = totalLength + ', ' + totalLength;

設置改變 circlestroke-dasharray,0為初始,而周長314為一整個圓(直徑為100可算得)。

注意

如果改變了圓環尺寸,以下需要更改

  • svg 容器的 widthheight,還有 viewBox
  • 兩個 circler 值 還有 stroke-width
  • #ringtransform=rotate() 里的后兩個參數為容器的中心坐標
  • #ringstroke-dasharray 里的最后一個參數當為圓的周長

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM