JSFiddle - React, Tailwind, and code Playground
HTML
<img id="test" src="http://content.worldcarfans.co/2008/6/medium/9080606.002.1M.jpg">
CSS
#test {
position: absolute;
left: 0;
}
JavaScript
const test = document.getElementById('test')
document.addEventListener('mousewheel', e => {
const delta = e.wheelDelta / 120
zoom(delta, e)
})
let _zoom = 1
function zoom(delta, e) {
// Zoom factor, so transform: scale() goes from 1 to 1.1, to 1.2...
let factor = 0.1
// Reverse zoom factor to negative values if scrollwheel in opposite direction
if (delta < 0) {
factor = factor * -1;
}
// The zoom to actually apply to the image, taking the initial zoom value (_zoom)
// into account
const nextZoom = _zoom + factor
const {
clientX,
clientY
} = e
const {
top,
left,
width,
height
} = test.getBoundingClientRect()
console.log('left')
console.log(left)
// Get mouse offset from image center
const offsetX = clientX - (left + width / 2)
const offsetY = clientY - (top + height / 2)
// Calculate image offset needed to realign the image with the
// mouse cursor.
const dx = offsetX * (factor / 2)
const dy = offsetY * (factor / 2)
const transform = `transform: scale(${nextZoom})`
_zoom = nextZoom
test.setAttribute('style', transform)
console.log('left - dx')
console.log(left - dx)
test.style.left = `${left - dx}px`
test.style.top = `${top - dy}px`
}