Here is zoom working example. I'd like the image to be zoomed on actual mouse position over image. How to achieve this? No libraries.
const image = document.querySelector('img');
const zoom = {
min: 1,
max: 3,
value: 1,
step: 0.1
};
image.addEventListener('wheel', event => {
event.preventDefault();
if (event.deltaY < 0) {
zoom.value = zoom.value >= zoom.max ? zoom.max : zoom.value + zoom.step;
} else if (event.deltaY > 0) {
zoom.value = zoom.value <= zoom.min ? zoom.min : zoom.value - zoom.step;
}
image.style.transform = `scale(${zoom.value})`
}
)
div {
width: 500px;
overflow: hidden;
}
img {
width: 100%;
}
<div>
<img src="https://picjumbo.com/wp-content/uploads/free-stock-photos-san-francisco-1080x720.jpg">
</div>
const image = document.querySelector('img');
const zoom = {
min: 1,
max: 3,
value: 1,
step: 0.1
};
var div = document.querySelector('div');
div.addEventListener('wheel', event => {
event.preventDefault();
if (event.deltaY < 0) {
zoom.value = zoom.value >= zoom.max ? zoom.max : zoom.value + zoom.step;
} else if (event.deltaY > 0) {
zoom.value = zoom.value <= zoom.min ? zoom.min : zoom.value - zoom.step;
}
image.style.transform = `scale(${zoom.value})`
var xPerc = (x * 100) / image.width;
var yPerc = (y * 100) / image.height;
image.style.transformOrigin = xPerc + '%' + ' ' + yPerc + '%';
}
)
var x, y;
div.addEventListener('mousemove', e => {
x = e.clientX - div.offsetLeft;
y = e.clientY - div.offsetTop;
})
div {
width: 500px;
overflow: hidden;
}
img {
width: 100%;
}
<div>
<img src="https://picsum.photos/200">
</div>
Played a little bit with your example and found out transform-origin
might do the trick. Added coordinates x,y relative to image's container and converted them to a percentage in order to set image's tranform-origin
style property.