Is there a way to control the browser's zoom level using JavaScript? I decided to create my own solution to override the default browser zoom behavior.
The current code works fine if starting from a scale of 1, but I'm facing an issue when already zoomed in and trying to zoom further by moving the cursor to another part of the image. The zoom focus seems to jump further than expected because changing the transform-origin causes the entire image to shift. Perhaps setting the transform-origin is not the most suitable approach...
var myDiv = document.querySelector(".container");
var img = myDiv.querySelector("img");
var scale = 1.0;
myDiv.addEventListener('wheel', function (ev) {
if(!ev.ctrlKey)
{
return;
}
ev.preventDefault();
const rect = myDiv.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
img.style.transformOrigin = x + "px " + y + "px"
scale += event.deltaY * -0.005;
// Apply scale transform
img.style.transform = `scale(${scale})`;
})
.container {
width: 600px;
height: 200px;
margin: auto;
border: 1px solid gray;
overflow: hidden;
}
img {
width: 100%;
transform: scale(1.0);
}
<div class="container">
<img src="https://picsum.photos/id/200/600/200">
</div>