JSFiddle - React, Tailwind, and code Playground
by Tan
HTML
width: <span id="result"></span> / position: <span id="result2"></span>
<div id="img">
<div id="img2" onmousemove="myFunction(event)"></div>
</div>
CSS
body {margin:0;}
#img {aspect-ratio:2/1;background-image:url('https://www.hloe.co.uk/sample.jpg');position:relative;}
#img2 {aspect-ratio:2/1;background-image:url('https://www.hloe.co.uk/sample.jpg');position:absolute;top:0;bottom:0;left:0;right:0;opacity:0.5;}
JavaScript
const bgzoom = 110;
const bgzoom2 = 120;
var container = document.getElementById("img2");
var container2 = document.getElementById("img");
function myFunction(event){
container.style.backgroundSize = bgzoom+"% "+bgzoom+"%";
container2.style.backgroundSize = bgzoom2+"% "+bgzoom2+"%";
// container width
var width = container.offsetWidth;
var height = container.offsetHeight;
var width2 = container2.offsetWidth;
var height2 = container2.offsetHeight;
var wdiv = (width / 100);
var wbgsize = wdiv * bgzoom;
var woffs = (wbgsize - width) / 100;
var wdiv2 = (width2 / 100);
var wbgsize2 = wdiv2 * bgzoom2;
var woffs2 = (wbgsize2 - width2) / 100;
var hdiv = (height / 100);
var hbgsize = hdiv * bgzoom;
var hoffs = (hbgsize - height) / 100;
var hdiv2 = (height2 / 100);
var hbgsize2 = hdiv2 * bgzoom2;
var hoffs2 = (hbgsize2 - height2) / 100;
var x = event.clientX;
var y = event.clientY;
var x2 = (x / wdiv);
var y2 = (y / hdiv);
var x2b = (x / wdiv2);
var y2b = (y / hdiv2);
var xpos = (woffs * x2);
var ypos = (hoffs * y2);
var xpos2 = (woffs2 * x2b);
var ypos2 = (hoffs2 * y2b);
//reverse percentage
var wpos = (woffs * 100) - xpos;
var hpos = (hoffs * 100) - ypos;
var wpos2 = (woffs2 * 100) - xpos2;
var hpos2 = (hoffs2 * 100) - ypos2;
container.style.backgroundPosition = "-"+wpos+"px -"+hpos+"px";
container2.style.backgroundPosition = "-"+wpos2+"px -"+hpos2+"px";
document.getElementById('result2').innerHTML = x2;
document.getElementById('result').innerHTML = width;
}
myFunction(event);
document.addEventListener("resize", setTimeout(myFunction(event), 1000));