vue实现移动轨迹
Vue 实现移动轨迹
在 Vue 中实现移动轨迹可以通过监听鼠标或触摸事件,记录移动路径并实时渲染。以下是具体实现方法:
监听事件并记录坐标
使用 @mousemove 或 @touchmove 事件监听移动动作,将坐标点存入数组:

<template>
<div
@mousemove="handleMove"
@touchmove="handleTouchMove"
ref="container"
>
<svg width="100%" height="100%">
<path :d="pathData" fill="none" stroke="blue" stroke-width="2"/>
</svg>
</div>
</template>
<script>
export default {
data() {
return {
points: [],
isDrawing: false
}
},
computed: {
pathData() {
if (this.points.length < 2) return '';
return `M ${this.points[0].x} ${this.points[0].y} L ${this.points.map(p => `${p.x} ${p.y}`).join(' L ')}`;
}
},
methods: {
handleMove(e) {
if (!this.isDrawing) return;
const rect = this.$refs.container.getBoundingClientRect();
this.points.push({
x: e.clientX - rect.left,
y: e.clientY - rect.top
});
},
handleTouchMove(e) {
if (!this.isDrawing) return;
const rect = this.$refs.container.getBoundingClientRect();
const touch = e.touches[0];
this.points.push({
x: touch.clientX - rect.left,
y: touch.clientY - rect.top
});
}
}
}
</script>
平滑轨迹处理
添加插值算法使轨迹更平滑,例如使用贝塞尔曲线:
computed: {
pathData() {
if (this.points.length < 3) return '';
let path = `M ${this.points[0].x} ${this.points[0].y}`;
for (let i = 1; i < this.points.length - 2; i++) {
const xc = (this.points[i].x + this.points[i + 1].x) / 2;
const yc = (this.points[i].y + this.points[i + 1].y) / 2;
path += ` Q ${this.points[i].x} ${this.points[i].y}, ${xc} ${yc}`;
}
return path;
}
}
性能优化
对于高频移动事件,使用防抖或节流控制更新频率:

import { throttle } from 'lodash';
methods: {
handleMove: throttle(function(e) {
// 处理逻辑
}, 16), // 约60fps
}
清除轨迹
添加重置功能清除已有轨迹:
methods: {
clearPath() {
this.points = [];
}
}
移动端适配
确保触摸事件正常工作:
<div
@touchstart="isDrawing = true"
@touchend="isDrawing = false"
@touchcancel="isDrawing = false"
></div>
通过以上方法可以实现基本的移动轨迹记录和展示功能,可根据实际需求扩展轨迹样式、存储或分析功能。






