1

I have an image 16000x9000 that is displayed on a simple page with predefined size for its container.

 myimage.onclick = function(e) {
        console.log(e.x, e.y);
    };
    <p>Image to use:</p>
    <img id="myimage" width="900px" height="500px" src="https://via.placeholder.com/150C/O https://placeholder.com/"> 

I want to click by image and get pixels coordinate. When I click by image I receive 900x500 as output of console.log and it's obvious incorrect data and means something else.

I expect to get the value approximate to original image width/height when I click on the bottom right corner.

How can I get this data?

TheUnKnown
  • 681
  • 5
  • 29
boden
  • 1,621
  • 1
  • 21
  • 42
  • 3
    Possible duplicate of [Find mouse position relative to element](https://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element) – Mike Doe Jun 04 '19 at 21:12
  • @emix I wouldn't say so – boden Jun 04 '19 at 21:14
  • You need to subtract offsets from your result, this might help - https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect – DannyMoshe Jun 04 '19 at 21:15
  • It doesn’t matter if it’s an image or a canvas or a div. The solution is there. Also fix your html, `900px` is not a valid value for the width attribute. – Mike Doe Jun 04 '19 at 21:19
  • @emix Why isn't it valid? – boden Jun 04 '19 at 21:23

2 Answers2

1

You can do some math to compare the size of the element and the original image size.

myimage.onclick = function(e) {
  var ratioX = e.target.naturalWidth / e.target.offsetWidth;
  var ratioY = e.target.naturalHeight / e.target.offsetHeight;

  var domX = e.x + window.pageXOffset - e.target.offsetLeft;
  var domY = e.y + window.pageYOffset - e.target.offsetTop;

  var imgX = Math.floor(domX * ratioX);
  var imgY = Math.floor(domY * ratioY);

  console.log(imgX, imgY);
};
<p>Image to use:</p>
<img id="myimage" width="900px" height="500px" src="https://via.placeholder.com/80x40">
abney317
  • 7,760
  • 6
  • 32
  • 56
0

It's a bit easier if you use offsetX and offsetY:

var ratioX = e.target.naturalWidth / e.target.offsetWidth;
var ratioY = e.target.naturalHeight / e.target.offsetHeight;
var imgX = Math.round(e.offsetX * ratioX);
var imgY = Math.round(e.offsetY * ratioY);
Richard
  • 1,803
  • 17
  • 17