SVG——入門,路徑描邊動畫

 

之前寫過一篇通過路徑的錨點改變實現圖形變化的動畫SVG——入門,路徑變形動畫,今天這一篇的demo是簡易的類似進度條之類的圖形,核心原理通過改變路徑的stroke-dasharray屬性,路徑的虛線描邊。

    .path:nth-of-type(1) {
        d: path("M5,5 305,5");
        stroke-dasharray: none;
    }

    .path:nth-of-type(2) {
        d: path("M5,35 305,35");
        stroke-dasharray: 15;
    }

    .path:nth-of-type(3) {
        d: path("M5,70 305,70");
        stroke-dasharray: 15, 5;
    }

    .path:nth-of-type(4) {
        d: path("M5,105 305,105");
        stroke-dasharray: 15,5 5,5 15,5 5,5;
    }

屬性值的順序大概就是 長度,間隙 長度,間隙 長度,間隙...

下面開始畫基礎部分,外側圓環和內側圓圈

    <svg xmlns="http://www.w3.org/2000/svg" class="svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <!-- 外圓 -->
        <circle class="" cx="150" cy="150" r="150" fill="#5d6771" /> 
        <!-- 內圓 -->
        <circle class="" cx="150" cy="150" r="90" fill="#2f3439" />
        <!-- 圓形路徑(動畫本體) -->
        <circle class="mycircle" cx="150" cy="150" r="120" />
    </svg>
    .svg {
        width: 300px;
        height: 300px;
        margin: 0 auto;
        display: block;
        background: #2f3439;
    }

    .mycircle {
        fill: none;
        stroke-width: 35px;
        stroke: #fffde8;
    }

那麼   stroke-dasharray屬性到底怎麼用呢,下面我們來試一下

stroke-dasharray:76px;

由此分析一下頁頭的gif圖

由圖中可以分析出,動畫的對象就是改變 stroke-dasharray屬性的長度和間隙,下面我們用animation寫出基礎動畫,

初始狀態是虛線的長度爲0,間隙是整段圓環的長度,這樣第二段線就看不到了,

那麼怎麼能計算出圓弧的周長呢?C = 2πR? 

NO NO NO

let mycircle = document.querySelector('.mycircle')
console.log('mycircle的周長爲' + mycircle.getTotalLength())

控制檯輸出753.6776123046875,我們可以取整,760

    @keyframes lineMove {
        0% {
            stroke-dasharray: 0, 760
        }

        100% {
            stroke-dasharray: 760, 760
        }
    }
animation: lineMove 4s ease-in-out 0s infinite;

大功告成,不過有點生硬,如果將線的兩端變的圓潤一點的話,那自然是最好不過

下面就要用到一個新的屬性, stroke-linecap,線段兩端的樣式屬性值

butt, round, square, inherit

灰色線爲描邊的實際長度,inherit爲繼承屬性

在這裏要講一下拐角的屬性  stroke-linejoin,屬性值也是四個 miter, round, bevel, inherit

言歸正傳,將圓角加在咱們的代碼上

    .mycircle {
        fill: none;
        stroke-width: 35px;
        stroke: #fffde8;
        stroke-dasharray:76px;
        stroke-linecap: round;
        animation: lineMove 4s ease-in-out 0s infinite;
    }

    @keyframes lineMove {
        0% {
            stroke-dasharray: 0, 760
        }

        60% {
            stroke-dasharray: 760, 760
        }
        100% {
            stroke-dasharray: 760, 760
        }
    }

一個簡單的路徑動畫demo就寫完啦!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章