vue实现飞线
Vue 实现飞线效果
飞线效果通常用于展示两点之间的动态连线,常见于地图、数据可视化等场景。以下是几种实现方式:
使用 SVG 和 CSS 动画
创建 SVG 路径并通过 CSS 或 JavaScript 实现动画效果:
<template>
<svg width="500" height="300">
<path
:d="pathData"
stroke="#ff0000"
stroke-width="2"
fill="none"
ref="flyLine"
/>
</svg>
</template>
<script>
export default {
data() {
return {
startPoint: { x: 50, y: 50 },
endPoint: { x: 450, y: 250 }
}
},
computed: {
pathData() {
const { startPoint, endPoint } = this
return `M${startPoint.x},${startPoint.y} L${endPoint.x},${endPoint.y}`
}
},
mounted() {
this.animateLine()
},
methods: {
animateLine() {
const path = this.$refs.flyLine
const length = path.getTotalLength()
path.style.strokeDasharray = length
path.style.strokeDashoffset = length
path.animate(
[{ strokeDashoffset: length }, { strokeDashoffset: 0 }],
{
duration: 2000,
iterations: Infinity
}
)
}
}
}
</script>
使用 Canvas 实现
通过 Canvas 绘制动态飞线:
<template>
<canvas ref="canvas" width="500" height="300"></canvas>
</template>
<script>
export default {
data() {
return {
start: { x: 50, y: 50 },
end: { x: 450, y: 250 },
progress: 0
}
},
mounted() {
this.drawLine()
this.animate()
},
methods: {
drawLine() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
const currentX = this.start.x + (this.end.x - this.start.x) * this.progress
const currentY = this.start.y + (this.end.y - this.start.y) * this.progress
ctx.beginPath()
ctx.moveTo(this.start.x, this.start.y)
ctx.lineTo(currentX, currentY)
ctx.strokeStyle = '#ff0000'
ctx.lineWidth = 2
ctx.stroke()
},
animate() {
const animateFrame = () => {
this.progress += 0.01
if (this.progress > 1) {
this.progress = 0
}
this.drawLine()
requestAnimationFrame(animateFrame)
}
animateFrame()
}
}
}
</script>
使用第三方库
对于复杂场景,可以考虑使用以下库:
- D3.js:强大的数据可视化库,支持各种路径动画
- Three.js:3D 飞线效果实现
- ECharts:内置飞线图类型
实现曲线飞线
创建贝塞尔曲线实现弧线效果:

// 在 SVG 方法中修改 pathData 计算
pathData() {
const { startPoint, endPoint } = this
const controlX = (startPoint.x + endPoint.x) / 2
const controlY = Math.min(startPoint.y, endPoint.y) - 50
return `M${startPoint.x},${startPoint.y} Q${controlX},${controlY} ${endPoint.x},${endPoint.y}`
}
性能优化建议
- 对于大量飞线,考虑使用 WebGL 方案
- 合理使用 requestAnimationFrame
- 避免频繁的 DOM 操作
- 必要时使用防抖/节流控制动画频率
以上方法可根据具体需求选择,SVG 方案适合简单场景,Canvas 适合复杂动画,第三方库则能快速实现专业效果。






