上一篇介绍了svg的引用,本文就介绍一个关于svg相关的动画,这个可以用来布局上,也可以使用在图标动态效果上,使用的相关技术是
stroke
svg描边处理,看后续能否有机会使用简单的svg描边动画
国外优秀案列:
1、svg描边动画原理
- stroke:SVG 中的 stroke 属性用来控制绘制描边的方式,我们也可以使用 CSS 来控制 SVG 的描边样式
- stroke-dasharray:可控制用来描边的虚线效果
- stroke-dashoffset:用来指定路径从开始位置的偏移量
2、操作
- 获取路径长度
var path = document.querySelector('path');
var length = path.getTotalLength();
- 设置样式,底下的1000就是svg中实际的长度,可以通过js获取
path {
dasharray: 1000;
stroke-dashoffset: 1000;
animation: dash 5s linear infinite;
}
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
简易案列
<style>
.drawing {
height: 800px;
width: 800px;
}
path {
stroke-width: 10px;
stroke-dasharray: 2400;
stroke-dashoffset: 2400;
animation: dash 2s linear 3s alternate infinite;
}
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
</style>
<svg class="drawing" viewBox="0 0 600 600">
<g fill="none" stroke-width="4" stroke="#aaa">
<path d="M0 0L600 0L600 600L0 600L0 0Z">
</path>
<path
d="M470 206C470 288.79 402.79 356 320 356C237.21 356 170 288.79 170 206C170 123.21 237.21 56 320 56C402.79 56 470 123.21 470 206Z">
</path>
<path d="M170 418L470 418L470 460.52L170 460.52L170 418Z"></path>
</g>
</svg>
<svg class="drawing" viewBox="0 0 1024 1024">
<g fill="none" stroke-width="4" stroke="#aaa">
<path
d="M171.309757 549.028173C146.751772 395.45579 231.111425 240.268869 381.752145 181.550641c111.636862-43.528816 232.004979-22.709763 317.235633 39.471225l-72.526783 117.478943 325.244596-1.253392L835.458797 0l-59.546741 96.426206c-125.572881-81.321771-296.756483-107.919173-446.653666-49.477117C121.577713 127.909713 2.038109 337.289905 25.640117 549.028173L171.309757 549.028173z">
</path>
<path
d="M852.687625 464.965935c24.536741 153.572383-59.780424 308.780549-210.421144 367.477532-102.693166 40.023567-215.859591 24.940376-302.874735-29.019211 16.570267-26.894818 65.53753-106.198415 65.53753-106.198415L55.169182 676.704203l148.006473 347.295797 62.053525-100.483797c125.551637 81.321771 279.591386 101.992117 429.488569 43.55006 207.638189-80.981868 327.220281-290.340816 303.618273-502.05784L852.687625 465.008423z">
</path>
</g>
</svg>