用SVG做一个Loading动画
概述
之前做加载效果都是用的html结合css,这次用SVG感觉还挺省事的
准备
开始做这个加载效果之前,需要先了解一下两个属性,stroke-dasharray和stroke-dashoffset
这两个属性可以看下面张鑫旭大神的文章,说的还是很清楚的
stroke-dasharray和stroke-dashoffset资料
实现
1、基础效果

代码:
<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偏移量的值实现
2、加速版

代码:
<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动画设置后逐渐减少
3、滚动版

代码:
<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添加一个旋转动画之后,整体的加载效果比基础版流畅多了
4、心电图版

代码:
<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相关动画,可以快速制作简单美观的动画效果