Home > Mobile >  How to convert image coordinates to cartesian coordinates using javaScript
How to convert image coordinates to cartesian coordinates using javaScript

Time:01-10

It is necessary by clicking on the picture below to determine the coordinates of the place where you clicked. The coordinates must be compared with the coordinate plane drawn on the picture. How can I do that with JavaScript?

coordinate-plane

I tried this answer. Formula: mx = C px * A, where mx - image coordinate, px - pixel coordinate, A - pixel size in X direction. It is not clear what is meant by the pixel coordinate in this case, and how to find it using JavaScript. Also I have this answer, but I have no idea how how to translate the coordinates of the picture, the countdown of which starts from the upper left corner to the coordinates I need.

CodePudding user response:

JavaScript offers event information of when the user interacts with the screen. What you can do is add an event listener on the <img> tag holding the picture like so:

document.getElementById("myImg").addEventListener("event type", (event) => {/* consume data */});

Depending on which device you want to work with, you have to set the event accordingly.

If you want to work with mobile device, they make use of Touch events, but if you want to work with laptops you should use Pointer events.

Once you have set your event handlers, you can access the event information in pixels with X and Y = 0px starting in the top left corner, Y growing when going down and X growing when going right. You should pay attention to your device Pixel Ratio because devices can render at a different pixel scale.

Once you handle this, you have to translate the pixels you have into coordinates, which should not be a problem. An easy solution can be to use different formulas after detecting if your event is situated in:

  • The top left part
  • The top right part
  • The bottom left part
  • The bottom right part

Example for the top-left part:

const imageSizePx = 1000;
console.log(window.devicePixelRatio);

document.getElementById("myImg").addEventListener("click", (event) => {
  // We are in the top left part
  if (event.clientX < imageSizePx / 2 && event.clientY < imageSizePx / 2) {
    console.log("X = ", getXTopLeft(event.clientX));
    console.log("Y = ", getYTopLeft(event.clientY));
  }
});

function getXTopLeft(pixels) {
  return -3.5 * (1 - pixels / (imageSizePx / 2));
}

function getYTopLeft(pixels) {
  return 3.5 * (1 - pixels / (imageSizePx / 2));
}
<!DOCTYPE html>
<html>
  <body style="margin: 0; padding: 0;">
    <img
      id="myImg"
      src="https://i.stack.imgur.com/dS7pa.png"
      width="1000"
      height="1000"
    />
  </body>
</html>

  • Related