https://www.jianshu.com/p/69dd56c28248
https://zhuanlan.zhihu.com/p/67031777
经过以上两文借鉴的动画,得到一个如何画飞线的思路,但是会有一个bug(只能绘制两点之间的贝塞尔曲线)。所以参照这个思路做了一下改良
大致步骤:
- 画一条线,具有动画
- 添加蒙版,和渐变色
- 线引用蒙版,线与蒙版一起做动画
借用一下知乎数澜大佬的demo:
demo
打开demo 以后修改一下代码:
M0,380C90,380 90,38 180,38
你会看见有一点奇怪的动画效果出来。
添加一下如何的代码:
const path2 = container
.append('path')
.attr('fill', 'none')
.attr('stroke', 'red')
.attr('d', 'M0,380C90,380 90,38 180,38')
.attr('id', 'line2')
你会看见飞线和你想要的path路径不在重合,没有沿预期的轨迹运动。
所以得到了一下解决方案:
const animate = () => {
container.select('#flyline').remove()
container.append('path')
.attr('stroke', '#19D0DC')
.attr('fill', 'none')
.attr('id', 'flyline')
.attr('stroke-width', '5px')
.attr('mask', "url(#Mask)")
.attr('d', 'M0,380C90,380 90,38 180,38')
.transition()
.duration(3000)
.attrTween('stroke-dasharray', function() {
const pathline = container.select('#flyline')
const len1 = pathline.node().getTotalLength()
return t => {
const p = pathline.node().getPointAtLength(t * len1)
mCircle.attr('cx', p.x).attr('cy', p.y)
return d3.interpolate(`0,${len1}`, `${len1},${len1}`)
}
})
}