Most of the code is from react-pinch-and-zoom
A react hook for pinch-to-zoom gesture interaction.
- Install this package as dependency
$ npm install react-use-pinch-zoom
- Import the hook, get container and content props from hook, and use them to whatever you want to pinch zoom
import usePinchZoom from 'react-use-pinch-zoom';
function App() {
const [containerProps, contentProps] = usePinchZoom<HTMLDivElement, HTMLImageElement>();
return (
<>
<h1>Pinch Zoom</h1>
<div {...containerProps}>
<img src="/image.jpg" {...contentProps} />
</div>
</>
);
}
- [Optional] You can customize style of element.
import usePinchZoom from 'react-use-pinch-zoom';
function App() {
const [containerProps, contentProps] = usePinchZoom<HTMLDivElement, HTMLImageElement>();
const { style: containerStyle, ...restContainerProps } = containerProps;
const newStyle = {
display: 'inline-block',
...containerStyle,
}
return (
<>
<h1>Pinch Zoom</h1>
<div style={newStyle} {...restContainerProps}>
<img src="/image.jpg" {...contentProps} />
</div>
</>
);
}
name | Type | Default |
---|---|---|
minZoomScale | number | 1.0 |
maxZoomScale | number | 4.0 |
onTransform | (transform: Transform) => void | undefined |
import usePinchZoom, { PinchZoomTypes } from 'react-use-pinch-zoom';
const [containerProps, contentProps] = usePinchZoom({
minZoomScale: 0.5,
maxZoomScale: 2.0,
onTransform: (transform: PinchZoomTypes.Transform) => {
console.log(transform);
},
});
containerProps
and contentProps
consist of below these.
const containerProps = {
onTouchStart,
onTouchMove,
onTouchEnd,
style: {
overflow: 'hidden',
touchAction: 'none',
},
ref,
}
const contentProps = {
style: {
willChange: 'transform',
transition: 'transform',
transform: `scale(${zoomScale}) translate(${x}px, ${y}px)`,
webkitTransform: `scale(${zoomScale}) translate(${x}px, ${y}px)`,
},
ref,
}
react-use-pinch-zoom
takes control of touch event and modifies zoomScale
, x
and y
values in transform style string.