vue实现canvas动态轨迹
Vue 实现 Canvas 动态轨迹
在 Vue 中实现 Canvas 动态轨迹可以通过监听用户操作(如鼠标移动或触摸事件)并将轨迹实时绘制到 Canvas 上。以下是具体实现方法:
初始化 Canvas 和 Vue 组件
在 Vue 组件的 template 中定义一个 Canvas 元素,并为其绑定 ref 以便在脚本中操作:
<template>
<canvas ref="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"></canvas>
</template>
在 script 中初始化 Canvas 上下文并定义相关数据:

export default {
data() {
return {
isDrawing: false,
lastX: 0,
lastY: 0,
};
},
mounted() {
const canvas = this.$refs.canvas;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
this.ctx = canvas.getContext('2d');
},
};
实现绘制逻辑
定义绘制方法,通过事件监听动态更新轨迹:
methods: {
startDrawing(e) {
this.isDrawing = true;
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
},
draw(e) {
if (!this.isDrawing) return;
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(e.offsetX, e.offsetY);
this.ctx.stroke();
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
},
stopDrawing() {
this.isDrawing = false;
},
}
添加样式和动画效果
为轨迹添加样式(如颜色、线条粗细):

mounted() {
const canvas = this.$refs.canvas;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
this.ctx = canvas.getContext('2d');
this.ctx.strokeStyle = '#000000';
this.ctx.lineWidth = 2;
this.ctx.lineCap = 'round';
}
若需实现动画效果(如渐变轨迹),可以使用 requestAnimationFrame:
methods: {
animate() {
requestAnimationFrame(this.animate);
// 添加动画逻辑,如渐变色或动态效果
},
}
响应式调整
监听窗口大小变化,动态调整 Canvas 尺寸:
mounted() {
window.addEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
const canvas = this.$refs.canvas;
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
},
}
清除轨迹
添加清除画布的功能:
methods: {
clearCanvas() {
this.ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
},
}
通过以上步骤,可以在 Vue 中实现 Canvas 动态轨迹绘制,并支持自定义样式、动画和响应式调整。






