vue实现canvas拖拽
Vue 实现 Canvas 拖拽功能
基础 Canvas 设置
在 Vue 中创建一个 Canvas 元素,并初始化绘图上下文:
<template>
<canvas ref="canvas" @mousedown="startDrag" @mousemove="onDrag" @mouseup="endDrag"></canvas>
</template>
<script>
export default {
data() {
return {
isDragging: false,
selectedObject: null,
objects: [
{ x: 100, y: 100, width: 50, height: 50, color: 'red' }
]
}
}
}
</script>
绘制对象到 Canvas
在 mounted 钩子中初始化 Canvas 并绘制对象:

mounted() {
this.ctx = this.$refs.canvas.getContext('2d');
this.drawObjects();
},
methods: {
drawObjects() {
this.ctx.clearRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height);
this.objects.forEach(obj => {
this.ctx.fillStyle = obj.color;
this.ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
});
}
}
实现拖拽逻辑
添加拖拽相关的事件处理方法:
methods: {
startDrag(e) {
const mouseX = e.offsetX;
const mouseY = e.offsetY;
this.selectedObject = this.objects.find(obj =>
mouseX >= obj.x &&
mouseX <= obj.x + obj.width &&
mouseY >= obj.y &&
mouseY <= obj.y + obj.height
);
if (this.selectedObject) {
this.isDragging = true;
this.dragOffsetX = mouseX - this.selectedObject.x;
this.dragOffsetY = mouseY - this.selectedObject.y;
}
},
onDrag(e) {
if (!this.isDragging || !this.selectedObject) return;
this.selectedObject.x = e.offsetX - this.dragOffsetX;
this.selectedObject.y = e.offsetY - this.dragOffsetY;
this.drawObjects();
},
endDrag() {
this.isDragging = false;
this.selectedObject = null;
}
}
响应式调整 Canvas 尺寸
添加窗口大小变化时的处理:

mounted() {
this.resizeCanvas();
window.addEventListener('resize', this.resizeCanvas);
},
beforeDestroy() {
window.removeEventListener('resize', this.resizeCanvas);
},
methods: {
resizeCanvas() {
const canvas = this.$refs.canvas;
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
this.drawObjects();
}
}
性能优化
对于复杂场景,可以使用 requestAnimationFrame 优化渲染:
methods: {
onDrag(e) {
if (!this.isDragging || !this.selectedObject) return;
this.selectedObject.x = e.offsetX - this.dragOffsetX;
this.selectedObject.y = e.offsetY - this.dragOffsetY;
if (!this.rafId) {
this.rafId = requestAnimationFrame(() => {
this.drawObjects();
this.rafId = null;
});
}
}
}
触摸屏支持
添加触摸事件处理:
<canvas
ref="canvas"
@mousedown="startDrag"
@mousemove="onDrag"
@mouseup="endDrag"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
></canvas>
methods: {
handleTouchStart(e) {
e.preventDefault();
const touch = e.touches[0];
const rect = this.$refs.canvas.getBoundingClientRect();
this.startDrag({
offsetX: touch.clientX - rect.left,
offsetY: touch.clientY - rect.top
});
},
handleTouchMove(e) {
e.preventDefault();
const touch = e.touches[0];
const rect = this.$refs.canvas.getBoundingClientRect();
this.onDrag({
offsetX: touch.clientX - rect.left,
offsetY: touch.clientY - rect.top
});
},
handleTouchEnd() {
this.endDrag();
}
}
这个实现提供了完整的 Canvas 拖拽功能,包括鼠标和触摸支持,以及性能优化。可以根据具体需求调整对象检测逻辑或添加更多交互功能。






