Last active
June 18, 2024 17:22
-
-
Save w8r/033e207e8bad2034d712c40285b606a6 to your computer and use it in GitHub Desktop.
Wheel to pinch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function startGesture(gesture) { | |
console.log("start", gesture); | |
} | |
function doGesture(gesture) { | |
console.log("do", gesture); | |
} | |
function endGesture(g) { | |
console.log("end", gesture); | |
} | |
function normalizeWheel(e) { | |
let dx = e.deltaX; | |
let dy = e.deltaY; | |
// TODO: normalize dx, dy | |
return [dx, dy]; | |
} | |
const WHEEL_SCALE_SPEEDUP = 2; | |
const WHEEL_TRANSLATION_SPEEDUP = 2; | |
let gesture = false; | |
let timer; | |
window.addEventListener( | |
"wheel", | |
function (e) { | |
if (e.cancelable !== false) { | |
e.preventDefault(); | |
} | |
let [dx, dy] = normalizeWheel(e); | |
if (!gesture) { | |
gesture = { | |
origin: { x: e.clientX, y: e.clientY }, | |
scale: 1, | |
translation: { x: 0, y: 0 }, | |
}; | |
startGesture(gesture); | |
} | |
if (e.ctrlKey) { | |
// pinch-zoom | |
let factor = | |
dy <= 0 | |
? 1 - (WHEEL_SCALE_SPEEDUP * dy) / 100 | |
: 1 / (1 + (WHEEL_SCALE_SPEEDUP * dy) / 100); | |
gesture = { | |
origin: { x: e.clientX, y: e.clientY }, | |
scale: gesture.scale * factor, | |
translation: gesture.translation, | |
}; | |
} else { | |
// panning | |
gesture = { | |
origin: { x: e.clientX, y: e.clientY }, | |
scale: gesture.scale, | |
translation: { | |
x: gesture.translation.x - WHEEL_TRANSLATION_SPEEDUP * dx, | |
y: gesture.translation.y - WHEEL_TRANSLATION_SPEEDUP * dy, | |
}, | |
}; | |
} | |
doGesture(gesture); | |
if (timer) { | |
window.clearTimeout(timer); | |
} | |
timer = window.setTimeout(function () { | |
if (gesture) { | |
endGesture(gesture); | |
gesture = null; | |
} | |
}, 200); | |
}, | |
{ passive: false }, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment