博客原文連接css
以前作加載效果都是用的html結合css,此次用SVG感受還挺省事的html
開始作這個加載效果以前,須要先了解一下兩個屬性,stroke-dasharray和stroke-dashoffsetcss3
這兩個屬性能夠看下面張鑫旭大神的文章,說的仍是很清楚的svg
stroke-dasharray和stroke-dashoffset資料
wordpress
代碼:動畫
<svg width="100" height="100">
<style> #svg-loading-base circle { stroke-dasharray: 250; stroke-dashoffset: 250; animation: svg-loading-base 1s ease infinite; } @keyframes svg-loading-base { to { stroke-dashoffset: 0; opacity: 0.1; } } </style>
<g id="svg-loading-base">
<text x="50" y="55" style="text-anchor: middle; fill: #5CC9F5; font-size: 14px;">加載中</text>
<circle cx="50" cy="50" r="40" style="fill: none; stroke: #5CC9F5; stroke-width: 5px; stroke-dasharray: null; stroke-dashoffset: null" />
</g>
</svg>
複製代碼
這個基礎版比較簡單,就是單純經過stroke-dasharray和stroke-dashoffset兩個屬性來設置線段分隔長度和偏移量,而後使用animation動畫逐漸減小stroke-dashoffset偏移量的值實現ui
代碼:spa
<svg width="100" height="100">
<style> #svg-loading-fast circle { animation: svg-loading-fast 2s ease infinite; } @keyframes svg-loading-fast { from { stroke-dasharray: 250; stroke-dashoffset: 250; } to { stroke-dasharray: 0; stroke-dashoffset: 0; opacity: 0.5; } } </style>
<g id="svg-loading-fast">
<text x="50" y="55" style="text-anchor: middle; fill: #5CC9F5; font-size: 14px;">加載中</text>
<circle cx="50" cy="50" r="40" style="fill: none; stroke: #5CC9F5; stroke-width: 5px; stroke-dasharray: null; stroke-dashoffset: null" />
</g>
</svg>
複製代碼
基礎版比較單調,這個加速版就先不設置默認的stroke-dasharray和stroke-dashoffset,直接在animation動畫設置後逐漸減小3d
代碼:code
<svg width="100" height="100">
<style> #svg-loading-rolling circle { stroke-dasharray: 300; stroke-dashoffset: 300; animation: svg-loading-rolling 1.5s linear infinite; } @keyframes svg-loading-rolling { from { stroke-dasharray: 600; stroke-dashoffset: 600; transform: rotate(0); transform-origin: 50px 50px; } to { stroke-dashoffset: 0; transform: rotate(720deg); transform-origin: 50px 50px; opacity: 0.1; } } </style>
<g id="svg-loading-rolling">
<text x="50" y="55" style="text-anchor: middle; fill: #5CC9F5; font-size: 14px;">加載中</text>
<circle cx="50" cy="50" r="40" style="fill: none; stroke: #5CC9F5; stroke-width: 5px; stroke-dasharray: null; stroke-dashoffset: null" />
</g>
</svg>
複製代碼
除了加速版,還能夠弄一個滾動版,利用css3裏的rotate爲circle添加一個旋轉動畫以後,總體的加載效果比基礎版流暢多了
代碼:
<svg width="100" height="100">
<style> #svg-loading-polyline { stroke-dasharray: 400; stroke-dashoffset: 400; animation: svg-loading-polyline 1s linear infinite; } @keyframes svg-loading-polyline { from { stroke-dasharray: 600; stroke-dashoffset: 600; } to { stroke-dashoffset: 0; opacity: 0.1; } } </style>
<polyline id="svg-loading-polyline" points="10 90, 30 10, 40 70, 45 60, 55 80, 65 30, 80 80, 90 90" style="fill: none; stroke: #5CC9F5; stroke-width: 3px; stroke-dasharray: null; stroke-dashoffset: null" />
</svg>
複製代碼
固然也能夠用折線作一個心電圖版,效果也不錯
利用stroke-dasharray和stroke-dashoffset這兩個屬性製做動效至關實用,結合css3相關動畫,能夠快速製做簡單美觀的動畫效果