Skip to content

Instantly share code, notes, and snippets.

@w8r
Last active June 18, 2024 17:22
Show Gist options
  • Save w8r/033e207e8bad2034d712c40285b606a6 to your computer and use it in GitHub Desktop.
Save w8r/033e207e8bad2034d712c40285b606a6 to your computer and use it in GitHub Desktop.
Wheel to pinch
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