vue使用canvas画矩形并可以脱动
时间: 2023-09-03 22:07:39 浏览: 83
可以的,以下是实现的基本步骤:
1.在 Vue 组件中创建 canvas 元素
2.在 mounted 钩子函数中获取 canvas 元素并获取上下文对象
3.监听鼠标事件,记录鼠标位置
4.在鼠标移动时,清空画布并重新绘制矩形,使矩形跟随鼠标移动
5.在鼠标松开时,停止绘制,并记录矩形的位置和大小
6.使用 requestAnimationFrame 实现动画效果,让矩形平滑移动到目标位置
以下是一个简单的示例代码:
```
<template>
<canvas ref="canvas"></canvas>
</template>
<script>
export default {
mounted() {
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
this.canvas.width = 600;
this.canvas.height = 400;
this.rect = null;
this.isDragging = false;
this.canvas.addEventListener('mousedown', this.onMouseDown);
this.canvas.addEventListener('mousemove', this.onMouseMove);
this.canvas.addEventListener('mouseup', this.onMouseUp);
this.canvas.addEventListener('mouseleave', this.onMouseUp);
},
methods: {
onMouseDown(e) {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
if (this.rect && this.isInsideRect(x, y)) {
this.isDragging = true;
this.offsetX = x - this.rect.x;
this.offsetY = y - this.rect.y;
} else {
this.rect = { x, y, width: 0, height: 0 };
}
},
onMouseMove(e) {
if (this.isDragging) {
const rect = this.canvas.getBoundingClientRect();
const x = e.clientX - rect.left - this.offsetX;
const y = e.clientY - rect.top - this.offsetY;
this.rect.x = x;
this.rect.y = y;
this.redraw();
}
},
onMouseUp() {
if (this.isDragging) {
this.isDragging = false;
this.animateRect();
}
},
redraw() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
if (this.rect) {
this.ctx.fillStyle = '#f00';
this.ctx.fillRect(this.rect.x, this.rect.y, this.rect.width, this.rect.height);
}
},
animateRect() {
const start = performance.now();
const end = start + 500;
const from = { x: this.rect.x, y: this.rect.y };
const to = { x: 100, y: 100 };
const animate = () => {
const now = performance.now();
const progress = (now - start) / (end - start);
if (progress >= 1) {
this.rect.x = to.x;
this.rect.y = to.y;
this.redraw();
} else {
const x = from.x + (to.x - from.x) * progress;
const y = from.y + (to.y - from.y) * progress;
this.rect.x = x;
this.rect.y = y;
this.redraw();
requestAnimationFrame(animate);
}
};
animate();
},
isInsideRect(x, y) {
return x >= this.rect.x && x <= this.rect.x + this.rect.width && y >= this.rect.y && y <= this.rect.y + this.rect.height;
},
},
};
</script>
```
在这个示例中,我们监听了鼠标事件,记录了矩形的位置和大小,然后在 mousemove 事件中重新绘制矩形,实现了矩形跟随鼠标移动的效果。在 mouseup 事件中,我们记录了矩形的目标位置,并使用 requestAnimationFrame 实现了平滑移动的动画效果。
阅读全文