0

I have an image in my DOM and I want to get the mouse click coords relative to the image in its natural width and height not the one that fits the container. For example, when the mouse clicks on the image it gives back coords (50, 50) which are the actual click coords on the image in its actual dimensions.

Any idea how to attain this?

  • 1
    This may help answer your question: https://stackoverflow.com/questions/34867066/javascript-mouse-click-coordinates-for-image – dale landry May 29 '20 at 22:45

2 Answers2

1

I made a simple and easy script for you!

const getCoords = (e) => {

  e = (e||window.event);
  
  let absoluteCoords = {
    x: e.pageX - e.target.getBoundingClientRect().left,
    y: e.pageY - e.target.getBoundingClientRect().top
  }
  
  return {
    x: absoluteCoords.x / e.target.clientWidth * e.target.naturalWidth,
    y: absoluteCoords.y / e.target.clientHeight * e.target.naturalHeight
  };

}
<img src="https://wow.olympus.eu/webfile/img/1632/oly_testwow_stage.jpg?x=1024" onclick="console.log( getCoords(event) )"/>
Adnane Ar
  • 683
  • 7
  • 11
  • A preferred way of writing JavaScript Event handlers is by using `addEventListener`, not by disseminating untestable code inside HTML attributes. – Roko C. Buljan May 29 '20 at 23:26
  • Also `width: 100%` on an `img` tag, and the click coordinates will almost never get you a click coordinate within the Natural image boundaries. – Roko C. Buljan May 29 '20 at 23:28
  • 1
    Ah true! I didn't read all the question proprely. I actually did not see the `in its actual dimensions`! Not problem im going to fix it real quick. – Adnane Ar May 29 '20 at 23:30
0

After some scribbling here's how I solved it.

    $("#img-container img").click((e) => {
    // image reference
    const img = $("#img-container img");

    // consider scrolled page amount for later calcualtions
    const scrollTop = $("body").scrollTop();
    const scrollLeft = $("body").scrollLeft();

    // calculate click x, y coords 
    let x = e.pageX + scrollLeft - e.target.offsetLeft;
    let y = e.pageY + scrollTop - e.target.offsetTop;

    // get original image dimensions
    const originalWidth = e.target.naturalWidth;
    const originalHeight = e.target.naturalHeight;

    // calcualte the difference in dimensions with current image
    const deltaWidth = originalWidth / img.width();
    const deltaHeight = originalHeight / img.height();

    // multiply the difference with x,y coords
    x = Math.round(x * deltaWidth);
    y = Math.round(y * deltaHeight);

    console.log(x, y);

  });

thanks for everyone's help