vue实现飞线
Vue 实现飞线效果
飞线效果通常指在地图或界面上展示动态的连线动画,常用于数据可视化。以下是基于 Vue 的实现方法:
使用 SVG 和 CSS 动画
创建 SVG 路径并结合 CSS 动画实现飞线效果:
<template>
<svg width="500" height="300">
<path
:d="pathData"
stroke="#1890ff"
stroke-width="2"
fill="none"
class="fly-line"
/>
</svg>
</template>
<script>
export default {
data() {
return {
pathData: "M100,100 Q250,50 400,100"
}
}
}
</script>
<style>
.fly-line {
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: dash 3s linear forwards;
}
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
</style>
使用 Canvas 实现
通过 Canvas 绘制更复杂的飞线效果:
<template>
<canvas ref="canvas" width="800" height="500"></canvas>
</template>
<script>
export default {
mounted() {
this.drawFlyLine();
},
methods: {
drawFlyLine() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
let progress = 0;
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制起点和终点
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(100, 100, 5, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(700, 400, 5, 0, Math.PI * 2);
ctx.fill();
// 计算当前点位置
const x = 100 + (700 - 100) * progress;
const y = 100 + (400 - 100) * progress;
// 绘制连线
ctx.strokeStyle = '#1890ff';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(x, y);
ctx.stroke();
// 绘制移动点
ctx.fillStyle = 'green';
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI * 2);
ctx.fill();
progress += 0.01;
if (progress <= 1) {
requestAnimationFrame(animate);
}
};
animate();
}
}
}
</script>
使用第三方库
对于更复杂的需求,可以考虑使用专业可视化库:
- ECharts:
npm install echarts
import * as echarts from 'echarts';
export default {
mounted() {
const chart = echarts.init(this.$refs.chart);
chart.setOption({
series: [{
type: 'lines',
data: [{
coords: [[100, 100], [400, 400]],
lineStyle: {
color: '#a6c84c',
curveness: 0.2
}
}],
effect: {
show: true,
period: 4,
trailLength: 0.7,
symbol: 'arrow',
symbolSize: 10
}
}]
});
}
}
- D3.js:
npm install d3
import * as d3 from 'd3';
export default {
mounted() {
const svg = d3.select(this.$refs.svg);
svg.append("path")
.attr("d", "M100,100 Q250,50 400,100")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("stroke-dasharray", "1000")
.attr("stroke-dashoffset", "1000")
.transition()
.duration(3000)
.attr("stroke-dashoffset", "0");
}
}
注意事项
- 性能优化:大量飞线时考虑使用 Canvas 而非 SVG
- 交互处理:可添加鼠标事件实现交互效果
- 响应式设计:监听窗口大小变化并重绘
- 数据驱动:将飞线数据与组件数据绑定实现动态更新
以上方法可根据具体需求选择或组合使用,SVG 适合简单场景,Canvas 适合复杂动画,第三方库则提供更完整的解决方案。







