<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: {
handleClick(event) {
const rect = event.currentTarget.getBoundingClientRect();
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;
}
}