get real offset when clicking on resize image

Viewed 208

I'm working on a program that shows the photoshop window and when you click on the image, it will also gets the click pixels exactly where you clicked on the image and i'm doing this by giving relative positions:

$('#screen').on('click', function(e) {
  var offset = $(this).offset();
  const relativeX = e.pageX - offset.left
  const relativeY = e.pageY - offset.top
  console.log('X: '+relativeX+'\nY: '+relativeY)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="screen" src="https://i.ibb.co/9brxVbK/image-2020-12-16-081145.png">

This works fine and clicks exactly where i have clicked on the image, but the problem is when i resize the image to 100% height and width, the offset is not accurate anymore:

$('#screen').on('click', function(e) {
  var offset = $(this).offset();
  const relativeX = e.pageX - offset.left
  const relativeY = e.pageY - offset.top
  console.log('X: '+relativeX+'\nY: '+relativeY)
})
#screen {
  width: 100%;
  height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="screen" src="https://i.ibb.co/9brxVbK/image-2020-12-16-081145.png">

Lets say i want to click on the buttons on the left, it will click out of the window bounds.

How can i resize the image and get exactly the real offset?

1 Answers

My original comment:

You'll need to find out the image's original size and its new size and use those to determine the image's render scale. Determine which pixel they clicked in screen coordinates relative to the image's upper left corner. Scale that offset by the inverse of the image's scale.

Code based on that comment:

(()=>{
  const $screen = $('#screen');
  const src = $screen.attr('src');
  const img = new Image();
  img.onload = () => {
    $screen.on('click', function(e) {
      const scaleX = img.width / $screen.width();
      const scaleY = img.height / $screen.height();
      const offset = $screen.offset();
      const relativeX = (e.pageX - offset.left) * scaleX;
      const relativeY = (e.pageY - offset.top) * scaleY;
      console.log(`X: ${relativeX}\nY: ${relativeY}`);
    });
  };
  img.src = src;
})();
#screen {
    width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="screen" src="https://i.ibb.co/9brxVbK/image-2020-12-16-081145.png">

Related