vue 鼠标在画布v-stage上移动画布上有一矩形怎么判断鼠标是否移动到画布上的矩形的边框上
要判断鼠标是否移动到画布上矩形的边框上,可以通过监听鼠标移动事件,并使用鼠标的坐标与矩形的位置和大小进行比较。下面是一个示例代码:
<template>
<div>
<div ref="stage" @mousemove="checkMousePosition">
<div ref="rectangle" :style="rectangleStyle"></div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
mouseX: 0,
mouseY: 0,
rectangleX: 100,
rectangleY: 100,
rectangleWidth: 200,
rectangleHeight: 100,
};
},
computed: {
rectangleStyle() {
return {
position: 'absolute',
left: `${this.rectangleX}px`,
top: `${this.rectangleY}px`,
width: `${this.rectangleWidth}px`,
height: `${this.rectangleHeight}px`,
border: '1px solid black',
};
},
},
methods: {
checkMousePosition(event) {
this.mouseX = event.clientX;
this.mouseY = event.clientY;
if (
this.mouseX >= this.rectangleX &&
this.mouseX <= this.rectangleX + this.rectangleWidth &&
(this.mouseY === this.rectangleY || this.mouseY === this.rectangleY + this.rectangleHeight)
) {
console.log('鼠标在矩形的边框上');
}
},
},
};
</script>
在上面的代码中,我们通过监听鼠标移动事件@mousemove并在checkMousePosition方法中获取鼠标的坐标event.clientX和event.clientY。然后,我们判断鼠标的坐标是否在矩形的边框上,如果是,则打印出"鼠标在矩形的边框上"。
注意,这里我们假设画布和矩形的位置都是相对于视口(viewport)的绝对位置。如果不是,你可能需要根据具体情况进行坐标的转换。
原文地址: https://www.cveoy.top/t/topic/jdZh 著作权归作者所有。请勿转载和采集!