<template>
<div class="sandbox">
<div
class="road"
@click="handleClick($event)"
>
<div
v-for="(point, pointIndex) in markPoints"
:key="pointIndex + 'point'"
:style="getMarkPointStyle(point)"
>
<img src="~@/assets/img/home/icon-no1.png" alt="标记点" />
</div>
</div>
<el-dialog
:visible="isDistanceVisible"
title="两个标记点之间的距离"
@close="handleCloseDialog"
width="20%"
height="100px"
>
<p>{{ calculateDistance() }}</p>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
markPoints: [], // 存储标记点坐标的数组
isDistanceVisible: false, // 是否显示距离弹窗
currMarkPoints: [],
};
},
methods: {
// 这里有讲解,可以理解event.clientX - rect.left
handleClick(event) {
// event.currentTarget指向绑定事件的元素,即road元素; rect.left表示 road盒子的左边 相对于浏览器窗口左边缘的水平距离
const rect = event.currentTarget.getBoundingClientRect();
// event.clientX 鼠标指针相对于浏览器窗口左边缘的水平距离
// 因此event.clientX - rect.left:鼠标指针相对于road盒子左边缘的水平距离
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
this.markPoints.push({ x, y });
this.currMarkPoints.push({ x, y });
// 弹窗显示,刚画的两个点的距离
if (this.currMarkPoints.length === 2) {
this.isDistanceVisible = true;
}
},
// 给画的小点定位
getMarkPointStyle(point) {
return {
position: "absolute",
top: `${point.y}px`,
left: `${point.x}px`,
};
},
//计算两点之间的距离(刚画的两个点)
calculateDistance() {
if (this.currMarkPoints.length !== 2) {
return;
}
const point1 = this.currMarkPoints[0];
const point2 = this.currMarkPoints[1];
const distance = Math.sqrt(
Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2)
);
return `${distance.toFixed(2)} px`;
},
handleCloseDialog() {
this.isDistanceVisible = false;
this.currMarkPoints = [];
},
},
};
</script>
.sandbox {
.road {
display: flex;
align-items: center;
background-color: #f3eaea;
position: relative; // 要定位
width: 500px;
height: 500px;
}
}