最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get image pixel coordinates relative left top corner - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Nov 27, 2012 at 15:11 John TravoltaJohn Travolta 6044 gold badges9 silver badges17 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 6

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

here is a link that could help you out

http://www.emanueleferonato.com/2006/09/02/click-image-and-get-coordinates-with-javascript/

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

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:

$(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:

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

评论列表(0)

  1. 暂无评论