JavaScript获取图像鼠标点击坐标

24

任务要求编写一个包含JavaScript的HTML文件,该文件会随机展示上述图片之一。如果在浏览器中刷新页面,则应该获得另一张随机图片。现在任务要求,当用户在图像的任何位置单击时,显示一个警报窗口,显示单击发生的位置相对于图像的X和Y坐标。以下是我的代码:

<html>
<head>
<title>Assignment 2</title>
<script type="text/javascript">
  var imageURLs = [
       "p1.jpg"
     , "p2.jpg"
     , "p3.jpg"
     , "p4.jpg"
  ];
  function getImageTag() {
    var img = '<img src=\"';
    var randomIndex = Math.floor(Math.random() * imageURLs.length);
    img += imageURLs[randomIndex];
    img += '\" alt=\"Some alt text\"/>';
    return img;
  }
</script>
</head>
<body>
<script type="text/javascript">
  document.write(getImageTag());
</script>
</body>
</html>


这可能是以下 stackover 解决方案的重复:https://dev59.com/DHI95IYBdhLWcg3wyBCc - Samuel Toh
可能是 jQuery 获取元素内鼠标位置 的重复问题。 - Michał Perłakowski
大家好,我在这里看到一个jQuery标签,但实际上并没有使用jQuery... @ChristinaPetrovski 你是否正在使用jQuery? - J. Titus
4个回答

37

您实际上可以使用HTML来完成此操作。图像标签有一个名为ismap的属性。

该属性指定图像是服务器端图像映射的一部分。当单击此类地图时,单击坐标会作为url查询字符串发送到服务器。

为使其有效工作,必须将图像嵌套在链接下。以下是示例:

<a href="http://www.google.com">
    <img src="myimage.png" alt="My Image" ismap">
</a>

如果您无法使用图像映射,请使用JavaScript / jQuery解决方案。

首先,您需要在 body 标签底部包含jQuery库。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  

$(document).ready(function() {
    $("img").on("click", function(event) {
        var x = event.pageX - this.offsetLeft;
        var y = event.pageY - this.offsetTop;
        alert("X Coordinate: " + x + " Y Coordinate: " + y);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://vignette1.wikia.nocookie.net/seraphina/images/b/b2/Dragonseraphina.jpg/revision/latest?cb=20160103194957" height="200" width="200" alt="dragon">

监听 click 事件,将 event 作为参数传递。

event.pageX 属性返回鼠标指针相对于文档左边缘的位置。


1
那么我应该把它放在哪里呢?我是心理学专业的,对这方面没有任何经验。我应该把它放在我的getImageTag函数下面吗? - Christina Petrovski
1
您只需复制并粘贴我列出的代码。如果单击“运行代码片段”,您可以查看示例。 - Richard Hamilton
我正在尝试,但没有成功。你认为这是因为我的身体实际上没有Img吗?它们随机显示。 - Christina Petrovski
在我的情况下(WordPress网页),只有var y = evtent.pageY - $('#element').offset().top;才能导致完整的y像素范围。(我必须在图像前添加id="element"。)使用var y = event.pageY - this.offsetTop;,y值将不会从0开始,而是从一个偏移量开始。这个不想要的偏移量是由于网页内部的CSS代码body { padding-top: 0.6rem; }造成的。修改后的代码来自链接 - feli_x
对于 jQuery 解决方案,我更喜欢以下答案以获取相对于图像的像素坐标:https://dev59.com/X1sW5IYBdhLWcg3wg3qD#58568016 - ass-king some questions

26

地图解决方案只会给你客户端的像素坐标。如果您想获取相对于原始图像的像素坐标,您需要自然高度和自然宽度信息,这些信息具有原始图像的高度和宽度。

代码:

 // https://dev59.com/X1sW5IYBdhLWcg3wg3qD
  document.getElementById(imageid).addEventListener('click', function (event) {
    // https://dev59.com/63VC5IYBdhLWcg3wcwwm#288731
    bounds=this.getBoundingClientRect();
    var left=bounds.left;
    var top=bounds.top;
    var x = event.pageX - left;
    var y = event.pageY - top;
    var cw=this.clientWidth
    var ch=this.clientHeight
    var iw=this.naturalWidth
    var ih=this.naturalHeight
    var px=x/cw*iw
    var py=y/ch*ih
    alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
  });

$(document).ready(function() {
    $("img").on("click", function(event) {
        bounds=this.getBoundingClientRect();
        var left=bounds.left;
        var top=bounds.top;
        var x = event.pageX - left;
        var y = event.pageY - top;
        var cw=this.clientWidth
        var ch=this.clientHeight
        var iw=this.naturalWidth
        var ih=this.naturalHeight
        var px=x/cw*iw
        var py=y/ch*ih
        alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="https://upload.wikimedia.org/wikipedia/commons/7/77/Avatar_cat.png" height="256" width="256" alt="kitten">

例子

click on IMG at pixel (445.5,334.125) mouse pos (148.5,49) relative to boundingClientRect at (483.5,64) client image size: 640 x 480 natural image size: 1920 x 1080

使用getBoundingClientRect方法会得到+1分,因为没有这个方法,你将无法获取图像的真实屏幕位置。this.offsetLeft/Top只提供相对位置(在简单情况下可能是正确的值,但在更复杂的情况下不是),这并没有什么帮助。 - Juergen
1
滚动到图像底部后,返回的坐标超出了图像范围:“在像素点(510,664)处单击IMG,鼠标位置为(255,332),相对于boundingClientRect为(8,-69),客户端图像大小:256 x 256,自然图像大小:512 x 512”。 - Ivan Kovtun
非常感谢提供一个纯JS的解决方案! - Carrotman42
1
感谢这个好的解决方案!正如@IvanKovtun所指出的那样,如果图像的一部分滚动到屏幕外,这将给出错误的坐标,因为getBoundingClientRect是相对于视口的。为了解决这个问题,将var x = event.pageX - left更改为var x = event.pageX - left - window.scrollX,y也同理。(感谢这个stackoverflow答案。) - ELNJ

4
$(document).ready(function () {
    $("img").on("click", function (event) {

        $('#img_coordinate').html("X Coordinate: " + (event.pageX - this.offsetLeft) + "<br/> Y Coordinate: " + (event.pageY - this.offsetTop));
    });
});

html

<img src="img/sample.gif" />

<p id="img_coordinate"></p>

1

小叉子 ;)

 $(document).ready(function() {
  $('img').click(function(e) {
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();
       w =   $(this).prop("width");        // Width  (Rendered)
   h =  $(this).prop("height");        // Height (Rendered)
      nw =    $(this).prop("naturalWidth") ;  // Width  (Natural)
  nh =  $(this).prop("naturalHeight") ; // Height (Natural)
    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );
        x = Math.round((left*nw)/w);
    y = Math.round((top*nh)/h);
//    $('#img_coordinate').html("Left: " + left + " Top: " + top + "nw: "+nw+" nh: "+nh +"x: "+x+" y: "+y);
    $('#img_coordinate').html("click x: "+x+" y: "+y);

  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接