JSFiddle - React, Tailwind, and code Playground

by Darker

HTML

<img src="http://i.stack.imgur.com/FnmFD.png" id="ble"/><br />

<span><tt id="x">0</tt>X<tt id="y">0</tt></span>

<h2>Demonstrates pixel coordinate calculation</h2>
If you want to test, define CSS transformations in CSS panel. For <tt>&lt;image&gt;</tt> requires support for <tt>.naturalWidth</tt> property. Don't forget to replace <tt>.naturalWidth</tt> with <tt>.width</tt> for <tt>&lt;canvas&gt;</tt> usage.

CSS

img {
    /*position: relative;
    top:50;
    left:20*/
    width: 130px;
    height: 80px;
    
}


span {
    font-size: 12pt;
}
span tt {
    font-size: 15pt;
    margin: 0 5px 0 5px;
    display: inline-block;
    text-align:right;
    min-width:2em;
}

JavaScript

/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/
HTMLImageElement.prototype.relativeCoords = HTMLCanvasElement.prototype.relativeCoords = function(event) {
  var x,y;
  //This is the current screen rectangle of canvas
  var rect = this.getBoundingClientRect();

  //Recalculate mouse offsets to relative offsets
  x = event.clientX - rect.left;
  y = event.clientY - rect.top;
  //Also recalculate offsets of canvas is stretched
  var width = rect.right - rect.left;
  //I use this to reduce number of calculations for images that have normal size 
    
    //NOTE: for canvas, you can replace naturalWidth by width. for image however CSS properties alter the width property  
  if(this.naturalWidth!=width) {
    var height = rect.bottom - rect.top;
    //changes coordinates by ratio
    x = x*(this.naturalWidth/width);
    y = y*(this.naturalWidth/height);
  } 
  //Return as an array
  return [x,y];
}

console.log(document.getElementById("ble").width);
var img = document.getElementById("ble");
var x = document.getElementById("x");
var y = document.getElementById("y");
img.addEventListener("mousemove", function(event) {
    var coords = img.relativeCoords(event);
    x.innerHTML = Math.round(coords[0]);
    y.innerHTML = Math.round(coords[1]);
});