Javascript 如何在单击时获得传单图像叠加的像素坐标

Javascript 如何在单击时获得传单图像叠加的像素坐标,javascript,leaflet,overlay,Javascript,Leaflet,Overlay,我有一张传单地图,它由一个瓷砖层和一个半透明的彩色区域显示温度分布的图像覆盖层组成。覆盖层放置在瓷砖层内的特定边界处。 当我点击覆盖图上的某个地方时,我想知道该点的像素有什么颜色 我的问题是将单击的位置投影到imageOverlay上,这与imageOverlay到可见地图的偏移量和缩放级别有关。最终我想得到图像上的像素坐标(以自然分辨率) 代码大致如下所示: var imgUrl = 'https://somewhere.somewhere/myImage.png'; var tilesUrl

我有一张传单地图,它由一个瓷砖层和一个半透明的彩色区域显示温度分布的图像覆盖层组成。覆盖层放置在瓷砖层内的特定边界处。 当我点击覆盖图上的某个地方时,我想知道该点的像素有什么颜色

我的问题是将单击的位置投影到imageOverlay上,这与imageOverlay到可见地图的偏移量和缩放级别有关。最终我想得到图像上的像素坐标(以自然分辨率)

代码大致如下所示:

var imgUrl = 'https://somewhere.somewhere/myImage.png';
var tilesUrl = 'https://somewhere.somewhere/{z}/{x}/{y}.png';
var tilesBounds = [...];
var imgBounds = [...];
var latlng = [...];

var mymap = L.map('mapid').setView(latlng, 9);
L.tileLayer(tilesUrl, {
    attribution: 'TILES',
    maxZoom: 12,
    minZoom: 7,
    id: 'tiles',
    tms: true,
    maxBounds: tilesBounds
}).addTo(mymap);

var imgOverlay = L.imageOverlay(imgUrl, imgBounds {
    attribution: 'dataimg',
    opacity: '0.4',
    id: 'dataImg',
    interactive: true
}).addTo(mymap);

imgOverlay.on('click',
  (e) => {

    var x = ???;
    var y = ???;

    var color = getColorAt(x, y);

  }
)

一个可能的解决办法是

  • 获取当前大小的
  • 然后交叉相乘以确定相对于图像原始大小的坐标
例如,
imgWidth
imgHeight
是图像的原始尺寸:

imgOverlay.on('click', (leafletEvent) => {
    // see https://stackoverflow.com/a/42111623/1071630
    var e = leafletEvent.originalEvent;
    var rect = e.target.getBoundingClientRect();
    var zoomedX = e.clientX - rect.left; //x position within the element.
    var zoomedY = e.clientY - rect.top;  //y position within the element

    const x = Math.round(zoomedX * imgWidth / rect.width);
    const y = Math.round(zoomedY * imgHeight / rect.height);
    console.log(x, y);
});
var-map=L.map('map').setView([48.854,2.2922926],14);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png'{
属性:“©;贡献者”
}).addTo(地图);
常量边界=[[48.85,2.28],[48.86,2.29]]
常量imgOverlay=L.imageOverlay('https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Tour_Eiffel_en_mai_2014.JPG/450px-Tour_Eiffel_en_mai_2014.JPG",界限,{
署名:“Nicolas Halftermeyer/CC BY-SA(https://creativecommons.org/licenses/by-sa/3.0)',
id:'dataImg',
互动:真的
}).addTo(地图);
常数imgWidth=450,imgHeight=600;
imgOverlay.on('点击',(传单事件)=>{
//看https://stackoverflow.com/a/42111623/1071630
var e=事件。原始事件;
var rect=e.target.getBoundingClientRect();
var zoomedX=e.clientX-rect.left;//元素中的x位置。
var zoomedY=e.clientY-rect.top;//元素中的y位置
常数x=数学圆(zoomedX*imgWidth/rect.width);
常数y=数学圆(缩放*垂直/垂直高度);
document.getElementById('log').innerHTML+=x+,“+y+”
”; });
#映射{宽度:400px;高度:200px;}
#日志{位置:绝对;顶部:0;右侧:10px;宽度:100px;}