CSS zoom with center
HTML
<div id="app">
<div id="editor">
<img id="image" src="https://placehold.co/600x400"/>
</div>
</div>
CSS
#app{
background: #eee;
width: 800px;
height: 500px;
}
#editor{
position: relative;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
#image{
position: absolute;
top: 50%;
left: 50%;
transform-origin: center center;
transform: translate(-50%, -50%) translate(0px, 0px) scale(1);
}
JavaScript
window.onload=function(){
var scroll_zoom = new ScrollZoom()
}
function ScrollZoom(){
const editor = document.querySelector('#editor');
var minZoom = 0.2
var maxZoom = 3
var zoomStep = 0.2
var currentZoom = 1
var currentPos = {x:0,y:0}
editor.addEventListener('wheel', scrolled);
function scrolled(e){
e.preventDefault();
const direction = Math.max(-1, Math.min(1, e.deltaY));
if (direction > 0 ? currentZoom <= minZoom : currentZoom >= maxZoom) return;
const image = document.querySelector('#image');
const imageRect = image.getBoundingClientRect();
const newZoom = parseFloat((direction > 0 ? currentZoom - zoomStep : currentZoom + zoomStep).toFixed(1))
const scaleRatio = newZoom/currentZoom;
// image center coordinates to count cursor (x, y) relatively from center of the image
const imageCenterX = imageRect.width / 2;
const imageCenterY = imageRect.height / 2;
// cursor position relative from image center
const cursorX = e.clientX - imageRect.left - imageCenterX;
const cursorY = e.clientY - imageRect.top - imageCenterY;
// coordinates adjusted by 20%/-20%
const adjustedX = cursorX * (1 - scaleRatio);
const adjustedY = cursorY * (1 - scaleRatio);
// absolute linear movement, simply add to previous position
const newX = currentPos.x + adjustedX;
const newY = currentPos.y + adjustedY;
update(newZoom, newX, newY)
}
function update(newZoom,newPosX,newPosY){
currentZoom = newZoom;
currentPos = {x:newPosX,y:newPosY}
document.getElementById('image').style.transform = `translate(-50%, -50%) translate(${currentPos.x}px, ${currentPos.y}px) scale(${newZoom})`
}
}