A script to allow custom touch-screen pinch to zoom functionality on an element-by-element basis rather than zooming the whole page.
<script src="https://adil.hanney.org/repo/PinchToZoom.js" type="module"></script>
JavaScript: PinchToZoom.js
TypeScript: PinchToZoom.ts
You can view a real life usage of PinchToZoom.js in my Nonogram PWA.
nextUse a phone or tablet to try the pinch-to-zoom functionality on this box.
import {allowPinchToZoom, PinchToZoomHandler} from "./lib/PinchToZoom";
let square: HTMLElement;
let pinchToZoomHandler: PinchToZoomHandler = null;
window.addEventListener("load", function() {
square = document.querySelector("#square");
pinchToZoomHandler = allowPinchToZoom(square);
});
import {allowPinchToZoom} from "./lib/PinchToZoom.js";
let square;
let pinchToZoomHandler = null;
window.addEventListener("load", function() {
square = document.querySelector("#square");
pinchToZoomHandler = allowPinchToZoom(square);
});
The below demo shows the scale
and offset
values when the
PinchToZoomHandler.onChange
function is called, rounded to 2 decimal places.
Note that the offset
is the position of the midpoint of the two fingers
relative to the midpoint of the element's original position, and does not change with scale
.
1.00x
(0.00, 0.00)
pinchToZoomHandler = allowPinchToZoom(square);
pinchToZoomHandler.onChange = (scale: number, offset: {x: number, y: number}) => {
console.log(scale, offset);
};
pinchToZoomHandler = allowPinchToZoom(square);
pinchToZoomHandler.onChange = (scale, offset) => {
console.log(scale, offset);
};
By default the element will not return to its original size after
the pinch ends. This demo sets the reflexive
flag to true
.
pinchToZoomHandler = allowPinchToZoom(square);
pinchToZoomHandler.reflexive = true;
pinchToZoomHandler = allowPinchToZoom(square);
pinchToZoomHandler.reflexive = true;
By default, desktop users can zoom in and out using the scroll wheel.
This functionality sometimes might not be needed on desktop ‐ or you don't want to get in the way
of scrolling through the page ‐ in which case you can set the isScrollZoomEnabled
flag to false
.
pinchToZoomHandler = allowPinchToZoom(square);
pinchToZoomHandler.isScrollZoomEnabled = false;
pinchToZoomHandler = allowPinchToZoom(square);
pinchToZoomHandler.isScrollZoomEnabled = false;