vue实现移动轨迹
实现移动轨迹的基本思路
在Vue中实现移动轨迹通常涉及监听用户触摸或鼠标事件,记录坐标点,并通过动画或路径绘制展示轨迹。以下是具体实现方法:
监听触摸/鼠标事件
通过@touchstart、@touchmove或@mousedown、@mousemove事件获取坐标:

<template>
<div
@touchstart="handleStart"
@touchmove="handleMove"
@mousedown="handleStart"
@mousemove="handleMove"
></div>
</template>
<script>
export default {
data() {
return {
points: [],
isDrawing: false
}
},
methods: {
handleStart(e) {
this.isDrawing = true;
this.addPoint(e);
},
handleMove(e) {
if (this.isDrawing) this.addPoint(e);
},
addPoint(e) {
const point = {
x: e.touches ? e.touches[0].clientX : e.clientX,
y: e.touches ? e.touches[0].clientY : e.clientY
};
this.points.push(point);
}
}
}
</script>
绘制轨迹路径
使用Canvas或SVG动态绘制路径。以Canvas为例:
<template>
<canvas
ref="canvas"
@touchstart="handleStart"
@touchmove="handleMove"
@touchend="handleEnd"
></canvas>
</template>
<script>
export default {
mounted() {
this.ctx = this.$refs.canvas.getContext('2d');
this.resizeCanvas();
window.addEventListener('resize', this.resizeCanvas);
},
methods: {
resizeCanvas() {
this.$refs.canvas.width = window.innerWidth;
this.$refs.canvas.height = window.innerHeight;
},
handleStart(e) {
const { x, y } = this.getPosition(e);
this.ctx.beginPath();
this.ctx.moveTo(x, y);
},
handleMove(e) {
const { x, y } = this.getPosition(e);
this.ctx.lineTo(x, y);
this.ctx.stroke();
},
getPosition(e) {
return {
x: e.touches ? e.touches[0].clientX : e.clientX,
y: e.touches ? e.touches[0].clientY : e.clientY
};
}
}
}
</script>
平滑轨迹处理
通过贝塞尔曲线或插值算法平滑轨迹:

// 二次贝塞尔曲线示例
drawSmoothPath() {
this.ctx.beginPath();
this.ctx.moveTo(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;
this.ctx.quadraticCurveTo(this.points[i].x, this.points[i].y, xc, yc);
}
this.ctx.stroke();
}
轨迹动画回放
使用requestAnimationFrame实现轨迹回放:
animatePath() {
let index = 0;
const animate = () => {
if (index >= this.points.length) return;
this.ctx.lineTo(this.points[index].x, this.points[index].y);
this.ctx.stroke();
index++;
requestAnimationFrame(animate);
};
animate();
}
性能优化建议
对于高频坐标采集,使用防抖或节流控制绘制频率:
import { throttle } from 'lodash';
methods: {
handleMove: throttle(function(e) {
this.addPoint(e);
}, 16) // 约60fps
}
移动端适配注意事项
- 添加
touch-action: noneCSS防止浏览器默认行为 - 使用
passive: true提高滚动性能 - 处理
touchend和touchcancel事件确保轨迹完整
以上方法可根据具体需求组合使用,实现从基础轨迹绘制到高级动画效果的完整解决方案。






