vue实现动态飞线
Vue 实现动态飞线效果
动态飞线效果常用于数据可视化或地图展示中,通过动画线条连接两个坐标点。以下是基于 Vue 和 Canvas 的实现方法:
安装依赖
需要安装动画库 gsap 和绘图工具库 fabric.js:
npm install gsap fabric
基础实现代码
在 Vue 组件中创建 Canvas 画布并绘制飞线:

<template>
<div class="container">
<canvas ref="flylineCanvas" width="800" height="600"></canvas>
</div>
</template>
<script>
import { fabric } from 'fabric'
import { gsap } from 'gsap'
export default {
mounted() {
this.initFlyline()
},
methods: {
initFlyline() {
const canvas = new fabric.Canvas(this.$refs.flylineCanvas)
const startPoint = { x: 100, y: 100 }
const endPoint = { x: 500, y: 400 }
const line = new fabric.Line(
[startPoint.x, startPoint.y, startPoint.x, startPoint.y],
{
stroke: '#1890ff',
strokeWidth: 2,
selectable: false
}
)
canvas.add(line)
gsap.to(line, {
duration: 2,
x1: endPoint.x,
y1: endPoint.y,
onUpdate: () => canvas.renderAll(),
repeat: -1,
yoyo: true
})
}
}
}
</script>
曲线飞线实现
要实现贝塞尔曲线效果的飞线:
drawCurveFlyline() {
const canvas = new fabric.Canvas(this.$refs.flylineCanvas)
const path = new fabric.Path('', {
stroke: '#ff4d4f',
fill: '',
strokeWidth: 2
})
canvas.add(path)
let progress = 0
const animate = () => {
progress += 0.01
if (progress > 1) progress = 0
const start = { x: 100, y: 100 }
const end = { x: 700, y: 500 }
const cp1 = { x: 300, y: 0 }
const cp2 = { x: 500, y: 600 }
const point = this.cubicBezier(start, cp1, cp2, end, progress)
path.set('path', `M ${start.x} ${start.y} Q ${cp1.x} ${cp1.y} ${point.x} ${point.y}`)
canvas.renderAll()
requestAnimationFrame(animate)
}
animate()
},
cubicBezier(p0, p1, p2, p3, t) {
const x = Math.pow(1-t,3)*p0.x + 3*Math.pow(1-t,2)*t*p1.x + 3*(1-t)*Math.pow(t,2)*p2.x + Math.pow(t,3)*p3.x
const y = Math.pow(1-t,3)*p0.y + 3*Math.pow(1-t,2)*t*p1.y + 3*(1-t)*Math.pow(t,2)*p2.y + Math.pow(t,3)*p3.y
return { x, y }
}
使用第三方库
对于更复杂的效果,可以使用专业的地图飞线库:

-
安装
echarts:npm install echarts -
实现地图飞线:
initEchartsFlyline() { const chart = this.$echarts.init(this.$refs.flylineChart) const option = { series: [{ type: 'lines', coordinateSystem: 'geo', effect: { show: true, period: 6, trailLength: 0.7, symbolSize: 3 }, lineStyle: { color: '#ffba00', width: 1, curveness: 0.2 }, data: [{ coords: [[116.46, 39.92], [113.65, 34.76]], lineStyle: { color: '#ff0000' } }] }] } chart.setOption(option) }
性能优化建议
- 使用
requestAnimationFrame替代setInterval - 对于大量飞线,考虑使用 WebGL 渲染
- 动画结束后及时清除不需要的对象
- 使用防抖控制高频渲染
以上方法可根据具体需求调整参数,如飞线颜色、宽度、动画时长等。实际项目中可能需要结合地图坐标系统进行位置转换。






