Open ghigt opened 9 months ago
HTML
<button onclick="reset()">reset</button>
<button onclick="zoomIn()">zoom in</button>
<button onclick="zoomOut()">zoom out</button>
<div class="wrapper">
<div class="canvas">
<div class="box">Scale me with your mouse wheel.</div>
</div>
</div>
css
body {
min-height: 100vh;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
}
.wrapper {
width: 400px;
min-height: 100vh;
border: 1px solid grey;
overflow: hidden;
}
.canvas {
width: 100%;
height: 100%;
outline: 1px solid red;
outline-offset: -1px;
}
.box {
width: 105px;
height: 105px;
background: #cdf;
padding: 5px;
}
JS
function zoom(event) {
event.preventDefault();
if ((currentEvent === undefined || currentEvent === 'scale') && event.deltaX == 0 && event.deltaY && event.deltaY > -1 && event.deltaY < 1) {
console.log('scale', currentEvent);
currentEvent = 'scale';
scale += event.deltaY * -0.01;
scale = Math.min(Math.max(0.125, scale), 4);
} else if (currentEvent === undefined || currentEvent === 'translate') {
console.log('translate', currentEvent);
currentEvent = 'translate';
x -= event.deltaX;
y -= event.deltaY;
} else {
return;
}
clearTimeout(timeoutEvent);
timeoutEvent = setTimeout(() => {
currentEvent = undefined;
}, 300);
// Apply scale transform
var t = `scale(${scale}) translateX(${x}px) translateY(${y}px)`;
el.style.transform = t;
}
function reset() {
scale = 1;
x = 0;
y = 0;
el.style.transform = `scale(${scale}) translateX(${x}px) translateY(${y}px)`;
}
function zoomIn() {
scale = Math.min(scale + 0.1, 1.5);
el.style.transform = `scale(${scale}) translateX(${x}px) translateY(${y}px)`;
}
function zoomOut() {
scale = Math.max(scale - 0.1, 0.5);
el.style.transform = `scale(${scale}) translateX(${x}px) translateY(${y}px)`;
}
let timeoutEvent;
let currentEvent;
let scale = 1;
let x = 0;
let y = 0;
const el = document.querySelector(".canvas");
const elWrapper = document.querySelector(".wrapper");
elWrapper.onwheel = zoom;