javascript - 如何相对于底层图像绝对定位形状元素?
问题描述
该页面有一个居中的图像——一张地图——我需要弄清楚如何在该地图上用小点标记兴趣点。
我的计划是用非常小的圆形元素绘制点,但是我如何定位它们,以便每次将网页加载到不同尺寸的屏幕上时它们会位于地图上的同一个位置?如果可以的话,我只会将点 photoshop 到图像上,但我需要编写 javascript 以使点具有交互性(在鼠标悬停时显示文本框描述),这样就行不通了。
<!DOCTYPE html>
<html>
<head> <meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="example.css" />
</head>
<body>
<img src="example.jpg" style="margin-left:auto;margin-right:auto;"></img>
</body>
解决方案
如果您的点是动态的并且您不能在 css 中设置它们,您可以使用画布。这是一个静态示例,如果需要,它可以转换为动态,可能比使用 css 以百分比定位要多得多,所以如果你知道你的兴趣点位置,你应该使用 CSS,如果它们是动态画布是一个不错的选择
code bellow...
// You will need the background of the map and an array of points of interest
// containing x and y coordinates relative to the map
const mapImageUrl = 'http://via.placeholder.com/500x300'
const pointsOfInterest = [
{name:'point1', x:420, y:50},
{name:'point2', x:50, y:134},
{name:'point3', x:100, y:200}
]
// get refference to the canvas and to its context
const canvas = document.getElementById('map')
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
// create a new image element that would hold your background
var mapImg = new Image();
// this block executes when the image is loaded
mapImg.onload = function () {
//setting the canvas size to the image size
canvas.width = mapImg.width;
canvas.height = mapImg.height;
//drawing the image to the canvas
ctx.drawImage(mapImg, 0, 0);
//for each point draw a red dot positioned to pointsOfInterest[i].x, pointsOfInterest[i].y
//here you could alose use the point of interest name or whatever you have availible on your json
for(let i = 0; i < pointsOfInterest.length; i ++) {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(pointsOfInterest[i].x, pointsOfInterest[i].y,15,0,2*Math.PI);
ctx.stroke();
ctx.fill();
}
};
// set the url of the image, once loaded it will trigger image.onload
mapImg.src = mapImageUrl;
html, body {
height: 100%;
}
.mapContainer {
display: flex;
align-items: middle;
justify-content: center;
margin: 0;
height: 100%;
flex-wrap: wrap;
}
#map{
align-self: center
}
<div class="mapContainer">
<canvas id="map"> </canvas>
</div>