PinchToZoom.js

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.

next

Default behaviour

Use a phone or tablet to try the pinch-to-zoom functionality on this box.

TypeScript

import {allowPinchToZoom, PinchToZoomHandler} from "./lib/PinchToZoom"; let square: HTMLElement; let pinchToZoomHandler: PinchToZoomHandler = null; window.addEventListener("load", function() { square = document.querySelector("#square"); pinchToZoomHandler = allowPinchToZoom(square); });

JavaScript

import {allowPinchToZoom} from "./lib/PinchToZoom.js"; let square; let pinchToZoomHandler = null; window.addEventListener("load", function() { square = document.querySelector("#square"); pinchToZoomHandler = allowPinchToZoom(square); });
next

Event handler for pinch change

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)

TypeScript

pinchToZoomHandler = allowPinchToZoom(square); pinchToZoomHandler.onChange = (scale: number, offset: {x: number, y: number}) => { console.log(scale, offset); };

JavaScript

pinchToZoomHandler = allowPinchToZoom(square); pinchToZoomHandler.onChange = (scale, offset) => { console.log(scale, offset); };
next

Reflexive

By default the element will not return to its original size after the pinch ends. This demo sets the reflexive flag to true.

TypeScript

pinchToZoomHandler = allowPinchToZoom(square); pinchToZoomHandler.reflexive = true;

JavaScript

pinchToZoomHandler = allowPinchToZoom(square); pinchToZoomHandler.reflexive = true;
next

Zooming with the scroll wheel (beta)

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.

TypeScript

pinchToZoomHandler = allowPinchToZoom(square); pinchToZoomHandler.isScrollZoomEnabled = false;

JavaScript

pinchToZoomHandler = allowPinchToZoom(square); pinchToZoomHandler.isScrollZoomEnabled = false;
Back to top