简体   繁体   English

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

[英]get image pixel coordinates relative left top corner

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构造中有什么东西可以用来获得这个逻辑吗?

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);

Use Jquery $('#id').offset() to get element position relative to window, or use $('#id').position() to get element top,left relative to parent element. 使用Jquery $('#id')。offset()来获取相对于窗口的元素位置,或者使用$('#id')。position()来获取元素top,left相对于父元素。 Also take a look at this question , providing answer in pure (vanilla) javascript. 另外看看这个问题 ,提供纯(香草)javascript的答案。 Here is jsFiddle example 这是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);
    });
});

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};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM