solid-awesome-hooks
Version:
A collection of awesome hooks for solid-js
48 lines (47 loc) • 2.08 kB
JavaScript
import { createEffect, createSignal, onCleanup } from "solid-js";
const getDistance = (event1, event2) => Math.hypot(event2.pageX - event1.pageX, event2.pageY - event1.pageY);
const DEFAULT_OPTIONS = {
preventTouchMoveEvent: true,
};
export const usePinchZoom = ({ onZoomIn, onZoomOut, options = DEFAULT_OPTIONS, }) => {
const [elementRef, setElementRef] = createSignal();
createEffect(() => {
const element = elementRef();
if (!element)
return;
let prevDistance = 0;
const handleTouchStart = (e) => {
if (e.touches.length === 2) {
prevDistance = getDistance(e.touches[1], e.touches[0]);
}
};
const handleTouchMove = (e) => {
if (e.touches.length === 2) {
if (options.preventTouchMoveEvent)
e.preventDefault();
// Calculate the distance between the two pointers
const currentPointDistance = getDistance(e.touches[1], e.touches[0]);
let shouldUpdatePrevDistance = false;
const distanceGrowthPX = Math.abs(currentPointDistance - prevDistance);
if (currentPointDistance - prevDistance > 0) {
onZoomIn?.(distanceGrowthPX);
shouldUpdatePrevDistance = true;
}
if (prevDistance - currentPointDistance > 0) {
onZoomOut?.(distanceGrowthPX);
shouldUpdatePrevDistance = true;
}
if (shouldUpdatePrevDistance) {
prevDistance = currentPointDistance;
}
}
};
element.addEventListener("touchstart", handleTouchStart);
element.addEventListener("touchmove", handleTouchMove);
onCleanup(() => {
element.removeEventListener("touchstart", handleTouchStart);
element.removeEventListener("touchmove", handleTouchMove);
});
});
return setElementRef;
};