D3方式:
原文: https://segmentfault.com/a/1190000000453579
通过这个方式,总是出现误差,首先是尾部被显示,然后消失,最后头部开始出现动画
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var path = svg.append("path") .attr("d", "M0,35.22131329279762Q68.79999999999998,208.6160083254511,85.99999999999999,208.61462731675533C111.79999999999998,208.61255580371167,146.19999999999996,37.44013393066172,171.99999999999997,35.20750320583997S232.2,193.72835097156664,258,193.7304224846103S318.19999999999993,32.82756488680316,343.99999999999994,35.22131329279762Q361.19999999999993,36.81714556346059,430,209.68874519124003") .attr("id","mypath"); var length = document.querySelector('#mypath').getTotalLength(); console.log("length="+length); path.style("fill", "none") .style("stroke", "#000") .style("stroke-dasharray", ""+length+", "+length+"") .transition() .duration(4000) .styleTween("stroke-dashoffset", function() { return d3.interpolateNumber(1000, 0); }); |
解释一下:其实两个实现的原理是一样的,都是使用了一点小技巧,分别使用css3.0和D3的动画改变svg:path的stroke-dasharray和stroke-dashoffset属性值,其中前一属性把path变成一条虚实相间的线,后一属性决定这条虚实相间线的起始位置,技巧是把虚实相间的间隔设置到超过整条Path长度,以上我取了1000
stroke-dasharray和stroke-dashoffset。
第一个属性设置虚线的间隔长度,让它等于自己本身,就是隐藏本身,在通过第二个属性(线段的偏移量),
通过不断增加和减少这个属性,使得线段慢慢出来。从而有了动画的效果。
CSS:方式:
js获得长度
1 2 3 4 5 6 7 8 9 10 11 |
var path = svg.append("path") .attr("d", "M0,35.22131329279762Q68.79999999999998,208.6160083254511,85.99999999999999,208.61462731675533C111.79999999999998,208.61255580371167,146.19999999999996,37.44013393066172,171.99999999999997,35.20750320583997S232.2,193.72835097156664,258,193.7304224846103S318.19999999999993,32.82756488680316,343.99999999999994,35.22131329279762Q361.19999999999993,36.81714556346059,430,209.68874519124003") .attr("id","mypath"); var length = document.querySelector('#mypath').getTotalLength(); console.log("length="+length); path.style("fill", "none") .style("stroke", "#000") .style("stroke-dasharray", length) .style("stroke-dashoffset", length); |
组合css
1 2 3 4 5 6 7 8 9 |
#mypath { /*四秒钟动画,执行一次,停止时保留状态*/ animation: pandy-svgorg-link-animation 4s ease 1 forwards; } @keyframes pandy-svgorg-link-animation { to { stroke-dashoffset: 0; } } |