在项目中我们总能遇到一些奇怪的需求。比如如标题描述一样在图片标记点位、文字、和自定义的形状?
1.先定义一块图片的区域~
<div class="mapContainer" id="mapContainer" ref="mapContainer">
<img
id="myBiaoZhu"
src="bg.jpg"
alt=""
style="height: 400px; width: 600px"
/>
<el-button type="text" @click="startBiaoZhu">开始标注</el-button>
<el-button type="text" @click="endBiaoZhu">标注完成</el-button>
</div>
如图:
首先定义我们展示到页面的对象
const state = reactive({
banMa: [
{
id: 1,
x: 240,
y: 302,
},
], //斑马线的数组
canBiaoZhu: false, //是否可以进行标注
pointColor: "red", //点的颜色
pointSize: 10, //点的大小
});
其次在页面挂载时将我们原有的数组渲染到页面上~
onMounted(() => {
for (let index = 0; index < state.banMa.length; index++) {
createMarker(
state.banMa[index].x,
state.banMa[index].y,
);
return;
}
});
点击图片时将点位固定
onMounted(() => {
document.getElementById("myBiaoZhu").onmousedown = (e) => {
e = e || window.event;
if (e.button !== 2) {
//判断是否右击
if (state.canBiaoZhu) {
//判断是否可以进行标注
var x = e.offsetX || e.layerX;
var y = e.offsetY || e.layerY;
var myImg = document.querySelector("#myBiaoZhu");
var currWidth = myImg.clientWidth;
var currHeight = myImg.clientHeight;
var ProportionWidthInImg = x / currWidth;
var ProportionHeightInImg = y / currHeight;
// console.log("图片比例高度:"+ProportionHeightInImg)
// console.log("图片比例宽度:"+ProportionWidthInImg)
state.banMa.push({
id: state.banMa.length + 1,
x,
y,
});
createMarker(x, y);
}
}
};
});
最后使用一个函数接收,并渲染到页面上。
function createMarker(x, y) {
var div = document.createElement("div");
div.className = "marker";
div.id = "marker" + state.banMa.length;
y = y + document.getElementById("myBiaoZhu").offsetTop - state.pointSize / 2;
x = x + document.getElementById("myBiaoZhu").offsetLeft - state.pointSize / 2;
div.style.width = state.pointSize + "px";
div.style.height = state.pointSize + "px";
div.style.backgroundColor = state.pointColor;
div.style.left = x + "px";
div.style.top = y + "px";
div.innerHTML = "<div>自定义名称</div>";
document.getElementById("mapContainer").appendChild(div);
}
好啦现在就可以去试试啦
版权声明:本文为IAmNotChangAn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。