Updated pinch map gesture to support movement and fix bug with drawing while pinching

This commit is contained in:
Mitchell McCaffrey 2020-05-25 17:26:36 +10:00
parent 012086745f
commit 92c14533f1

View File

@ -15,7 +15,7 @@ import MapStageContext from "../../contexts/MapStageContext";
import AuthContext from "../../contexts/AuthContext"; import AuthContext from "../../contexts/AuthContext";
const wheelZoomSpeed = 0.001; const wheelZoomSpeed = 0.001;
const touchZoomSpeed = 0.01; const touchZoomSpeed = 0.005;
const minZoom = 0.1; const minZoom = 0.1;
const maxZoom = 5; const maxZoom = 5;
@ -70,6 +70,9 @@ function MapInteraction({ map, children, controls, selectedToolId }) {
} }
} }
const pinchPreviousDistanceRef = useRef();
const pinchPreviousOriginRef = useRef();
const bind = useGesture({ const bind = useGesture({
onWheel: ({ delta }) => { onWheel: ({ delta }) => {
const newScale = Math.min( const newScale = Math.min(
@ -78,16 +81,41 @@ function MapInteraction({ map, children, controls, selectedToolId }) {
); );
setStageScale(newScale); setStageScale(newScale);
}, },
onPinch: ({ offset }) => { onPinch: ({ da, origin, first }) => {
const [d] = offset; const [distance] = da;
const [originX, originY] = origin;
if (first) {
pinchPreviousDistanceRef.current = distance;
pinchPreviousOriginRef.current = { x: originX, y: originY };
}
// Apply scale
const distanceDelta = distance - pinchPreviousDistanceRef.current;
const originXDelta = originX - pinchPreviousOriginRef.current.x;
const originYDelta = originY - pinchPreviousOriginRef.current.y;
const newScale = Math.min( const newScale = Math.min(
Math.max(1 + d * touchZoomSpeed, minZoom), Math.max(stageScale + distanceDelta * touchZoomSpeed, minZoom),
maxZoom maxZoom
); );
setStageScale(newScale); setStageScale(newScale);
// Apply translate
const stageTranslate = stageTranslateRef.current;
const layer = mapLayerRef.current;
const newTranslate = {
x: stageTranslate.x + originXDelta / newScale,
y: stageTranslate.y + originYDelta / newScale,
};
layer.x(newTranslate.x);
layer.y(newTranslate.y);
layer.draw();
stageTranslateRef.current = newTranslate;
pinchPreviousDistanceRef.current = distance;
pinchPreviousOriginRef.current = { x: originX, y: originY };
}, },
onDrag: ({ delta, xy, first, last }) => { onDrag: ({ delta, xy, first, last, pinching }) => {
if (preventMapInteraction) { if (preventMapInteraction || pinching) {
return; return;
} }