react hook for panning & zooming element
React hook for panning & zooming element
npm i -S use-pan-zoom
import React from 'react';
import usePanZoom from 'use-pan-zoom';
const App = () => {
const { elemRef, style } = usePanZoom();
return (
<div
ref={elemRef}
style={{
touchAction: 'none',
transformOrigin: '0 0',
transform: `translate3d(${style.x}px, ${style.y}px, 0) scale(${style.scale})`
}}
></div>
);
};
const values = usePanZoom(options);
values: (Object)
options: (Object)
-Infinity
Infinity
{ x: [-Infinity, Infinity], y: [-Infinity, Infinity] }
const App = () => {
const myRef = useRef();
const { elemRef } = usePanZoom();
return (
<div
ref={node => {
myRef.current = node;
elemRef(node);
}}
/>
);
};
If bounds are calculated based on the current scale, use scale
from parameters instead of style.scale
, because style
is a React State, the value could be staled until the next effect
e.g. limit pan zoom inside parentElement
usePanZoom({
bounds: ({ scale }) => {
return {
x: [parent.width - element.width * scale, 0],
y: [parent.height - element.height * scale, 0]
};
}
});