Javascript 获取图像像素坐标相对左上角

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13587184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:25:03  来源:igfitidea点击:

get image pixel coordinates relative left top corner

javascript

提问by John Travolta

I need to get image coordinates on click relative left top corner. So left top corner of the image is conditional 0,0 and then first pixel 1,0... 2..0 etc. Is there something in javascript construction I can use to get this logic?

我需要在点击相对左上角时获取图像坐标。所以图像的左上角是有条件的 0,0 然后第一个像素 1,0... 2..0 等等。javascript 构造中有什么东西可以用来获得这个逻辑?

回答by Rahul Tripathi

You can try something like this:-

你可以尝试这样的事情:-

  <img id="board" style="z-index: 0; left: 300;position: absolute; top: 600px" align=baseline     border=0 hspace=0 src="design/board.gif">

  function findPos(obj){
  var curleft = 0;
  var curtop = 0;

  if (obj.offsetParent) {
do {
    curleft += obj.offsetLeft;
    curtop += obj.offsetTop;
   } while (obj = obj.offsetParent);

return {X:curleft,Y:curtop};
 }
}

 findPos(document.getElementById('board'));
 alert(curleft);
 alert(curtop);

回答by LoonyNoob

offsetLeft and offsetTop return the position relative to the top/left corner of the document:

offsetLeft 和 offsetTop 返回相对于文档上/左角的位置:

function getCoordinates(elem) {
    var LeftPos = elem.offsetLeft;
    var TopPos = elem.offsetTop;
    return {X:LeftPos,Y:TopPos};
}

回答by Davor Zubak

Use Jquery $('#id').offset()to get element position relative to window, or use $('#id').position()to get element top,left relative to parent element. Also take a look at this question, providing answer in pure (vanilla) javascript. Here is jsFiddle example

使用 Jquery $('#id').offset()获取元素相对于窗口的位置,或使用$('#id').position()获取元素相对于父元素的顶部,左侧。也看看这个问题,用纯(香草)javascript 提供答案。这是 jsFiddle示例

HTML:

HTML:

<div id="xRes">Top:<span></span></div>
<div id="yRes">Left:<span></span></div>

<input type="button" id="getPos" value="Get X,Y"/>

<img src="http://www.katimorton.com/wp-content/uploads/2012/05/mr-happy.jpg" id="myImg"/>

JS:

JS:

$(document).ready(function () {

    $('#myImg').draggable();

    $('#getPos').on('click', function(){

        var xRes = $('#xRes span'),
            yRes = $('#yRes span'),

            image = $('img#myImg');

        xRes.html(image.offset().top);
        yRes.html(image.offset().left);
    });
});