[TOC]css
Demo项目下载html
看到网页中那种有如写字般的动画,以为挺好玩的,就找了下制做方法,也比较简单,在此记录一下; 先上几张图看看:git
stroke 定义边框颜色值; stroke-width 定义描边宽度; stroke-dashoarray 前一个数值表示dash,后一个数字表示gap长度(只写单个值表示dash/gap尺寸一致),往复循环; stroke-dashoffset 虚线开始时的偏移长度,正数则从路径起始点向前偏移,负数则向后偏移;github
stroke-dashoarray
属性,使svg图案的 dash 和 gap 长度大于等于最终图案长度值(记为len);stroke-dashoffset
的值直至为0,就出现了动画;主要使用到 path 标签,具体能够看 这里 ; 复杂点的图案就不建议手动书写,可采用第三方软件,导出成svg文件,删除无用代码便可,如: Inkscape 在线编辑markdown
可经过css或js来控制动画的实现,css比较简单,但图案的长度等参数不易掌控;svg
<style>
path {
stroke-dasharray: 610;//实线-间隔长度都是610(大于所画长度)
stroke-dashoffset: 610;//往前偏移610(超过图形长度),则初始显示为空白
animation: dash 5s linear;//添加动画,使偏移逐渐变为0,以显示完整图案
animation-fill-mode: forwards;//动画完成后保持不变
}
// 定义css动画,@keyframes yourName
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
</style>
复制代码
//代码获取长度并设置动画相关属性 var path = document.querySelector('path'); var len = path.getTotalLength(); console.log("总长度 : " + len); //定义实线和空白区域长度 path.style.strokeDasharray = len + 10; //定义初始dash部分相对起始点的偏移量,正数表示往前便宜 path.style.strokeDashoffset = len + 10; 复制代码
// 方式1:参考文章: https://jakearchibald.com/2013/animated-line-drawing-svg/ path.style.transition = path.style.WebkitTransition = 'none'; // Trigger a layout so styles are calculated & the browser // picks up the starting position before animating path.getBoundingClientRect(); path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset 5s ease-in-out'; path.style.strokeDashoffset = '0'; 复制代码
var initial_ts = new Date().getTime(); var duration = 5000; var draw = function () { var progress = (Date.now() - initial_ts) / duration; if (progress < 1) { path.style.strokeDashoffset = Math.floor(len * (1 - progress)); setTimeout(draw, 50); } }; draw(); 复制代码
var initial_ts = new Date().getTime(); var duration = 5000; var handle = 0; var animate = function () { var progress = (Date.now() - initial_ts) / duration; if (progress >= 1) { window.cancelAnimationFrame(handle); } else { path.style.strokeDashoffset = Math.floor(len * (1 - progress)); handle = window.requestAnimationFrame(animate); } }; animate(); 复制代码
方式3比较依赖系统刷新率,若硬件性能问题致使fps降低严重,则可能出现较严重卡顿现象wordpress
W3C SVG MDN-SVG Painting: Filling, Stroking and Marker Symbols Animated line drawing in SVG 用css定义svg的样式和动画 SVG SMIL animation动画详解oop