As I work on my web project, I am trying to achieve the functionality of zooming in a div
element centered around the mouse position while using the mouse wheel. I came across a helpful answer by @Tatarize on Zoom in on a point (using scale and translate), but I am having trouble implementing it accurately. The current issue is that the zoom and translation are not working as expected around the mouse position. Can anyone provide assistance?
window.onload = function() {
const STEP = 0.05;
const MAX_SCALE = 10;
const MIN_SCALE = 0.01;
const red = document.getElementById('red');
const yellow = red.parentNode;
let scale = 1;
yellow.onmousewheel = function (event) {
event.preventDefault();
let mouseX = event.clientX - yellow.offsetLeft - red.offsetLeft;
let mouseY = event.clientY - yellow.offsetTop - red.offsetTop;
const factor = event.wheelDelta / 120;
const oldScale = scale;
scale = scale + STEP * factor;
scale = Math.max(MIN_SCALE, Math.min(MAX_SCALE, scale));
const scaleChanged = scale - oldScale;
const offsetX = -(mouseX * scaleChanged);
const offsetY = -(mouseY * scaleChanged);
console.log(offsetX, offsetY);
red.style.transform = 'translate(' + offsetX + 'px, ' + offsetY + 'px)' + 'scale(' + scale + ')';
}
}
.yellow {
background-color: yellow;
width: 400px;
height: 200px;
}
.red {
background-color: red;
width: 100px;
height: 50px;
}
<div class="yellow">
<div id="red" class="red"></div>
</div>