How to get the intrinsic coordinates on an image mouse click

I’m currently working on a program that can generate a customizable image report. It needs to allow the user to click on areas in an image to specify certain areas used when generating the report.

One method of doing this would be to use a two dimensional drawing library, like Two.js. Unfortunately, these libraries require a lot of overhead when all that’s needed is for a user to specify a position on an image.

Luckily, there is a jQuery solution. And with a bit of extra work, it’s doable in pure JavaScript as well. It doesn’t require any libraries beyond jQuery.

I found this solution on StackOverflow with a quick Google search. Unfortunately, it will only give the location of the pixel on the HTML image element. This means that an image served at 1280×720, but displayed at half that size (640×360) would make a click on the bottom left corner of the image return an X/Y of 630 and 360, not the actual image pixel location, 1280 / 720.

My solution was to simply get the percentage location of the x any y axis click location off of the actual image width and height. This means that clicking the center would give me a percentage value of 0.5, instead of 315. Then, I multiply that percentage by the actual image width.

[codepen_embed height=”468″ theme_id=”default” slug_hash=”MWYvQxX” default_tab=”result” user=”scarabcoder”]See the Pen Get Clicked Location by Nicholas (@scarabcoder) on CodePen.[/codepen_embed]

$(document).ready(() => {
    .on("click", function(event) {
      let x = event.pageX - this.offsetLeft;
      let y = event.pageY - this.offsetTop;
      let xPercent = x / this.width;
      let yPercent = y / this.height;
      let actualX = xPercent * this.naturalWidth;
      let actualY = yPercent * this.naturalHeight;
      alert("X Coordinate: " + actualX + " Y Coordinate: " + actualY);

The image in the codepen is 1280×720, but the img HTML tag resizes the image to half that size.

Leave a Reply

Your email address will not be published. Required fields are marked *