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><image></tt> requires support for <tt>.naturalWidth</tt> property. Don't forget to replace <tt>.naturalWidth</tt> with <tt>.width</tt> for <tt><canvas></tt> usage.
CSS
img {
/*position: relative;
top:50;
left:20*/
width: 180px;
height: 120px;
border: 50pt solid black;
}
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();
var top = rect.top;
var bottom = rect.bottom;
var left = rect.left;
var right = rect.right;
//Subtract border size
// get its computed style
var styling=getComputedStyle(this,null);
// fetch the 4 border width values
var topBorder=parseInt(styling.getPropertyValue('border-top-width'),10);
var rightBorder=parseInt(styling.getPropertyValue('border-right-width'),10);
var bottomBorder=parseInt(styling.getPropertyValue('border-bottom-width'),10);
var leftBorder=parseInt(styling.getPropertyValue('border-left-width'),10);
console.log(left, leftBorder);
left+=leftBorder;
right-=rightBorder;
top+=topBorder;
bottom-=bottomBorder;
//Recalculate mouse offsets to relative offsets
x = event.clientX - left;
y = event.clientY - top;
//Also recalculate offsets of canvas is stretched
var width = right - 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 = bottom - top;
//changes coordinates by ratio
x = x*(this.naturalWidth/width);
y = y*(this.naturalWidth/height);
}
//Return as an array
return [x,y];
}
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]);
});