Multi-Touch Gestures
Handle pinch-to-zoom with the native Touch API. jQuery does not wrap multi-touch — access the touches array directly via originalEvent.
Handle pinch-to-zoom with the native Touch API. jQuery does not wrap multi-touch — access the touches array directly via originalEvent.
let initialDist = 0;
function dist(t) {
return Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY);
}
$("#zoomable").on("touchstart", e => {
if (e.originalEvent.touches.length === 2)
initialDist = dist(e.originalEvent.touches);
}).on("touchmove", e => {
if (e.originalEvent.touches.length === 2) {
e.preventDefault();
const scale = dist(e.originalEvent.touches) / initialDist;
$(this).css("transform", `scale(${Math.max(0.5, Math.min(scale, 4))})`)
}
});
Call e.preventDefault() in touchmove to prevent the browser from intercepting the pinch and zooming the page.