页面上的图像居中-地图-我需要弄清楚如何在地图上用小点标记兴趣点。
我的计划是用很小的圆形元素绘制点,但是如何在每次将网页加载到不同尺寸的屏幕上时将它们定位在地图上的同一位置?如果可以的话,我将把这些点照片化处理,但是我将需要编写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>
答案 0 :(得分:0)
将图像包裹在div中,给其position:relative
并绝对使用%值定位点(div)。
这是我留下的一个例子:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.map {
margin: 10px;
border: 5px solid red;
position: relative;
display: inline-block;
}
.map img {
max-width: 100%;
display: block;
}
.box {
width: 8%;
height: 8%;
background-image: url(http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg);
background-position: top center;
background-repeat: no-repeat;
background-size: contain;
position: absolute;
}
#pin-1 {
top: 25%;
left: 36%;
}
.box:hover>.pin-text {
display: block;
}
.pin-text {
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 75%;
white-space: nowrap;
display: none;
}
.pin-text h3 {
color: white;
text-shadow: 1px 1px 1px #000;
}
<div class="map">
<img src="https://www.homesinc.com/wp-content/uploads/2017/05/1.jpg" alt="" />
<div id="pin-1" class="box">
<div class="pin-text">
<h3>My House</h3>
</div>
</div>
</div>
答案 1 :(得分:0)
如果您的点是动态的,并且无法在CSS中设置它们,则可以使用canvas。这是一个静态示例,可以根据需要将其转换为动态示例,这可能比使用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>