0.0.4 • Published 3 years ago

react-use-pinch-zoom v0.0.4

Weekly downloads
8
License
MIT
Repository
github
Last release
3 years ago

license npm version npm downloads

Most of the code is from react-pinch-and-zoom

React-Use-Pinch-Zoom

A react hook for pinch-to-zoom gesture interaction.

Demo

Demo Webp

Demo Webpage

Usage

  1. Install this package as dependency
$ npm install react-use-pinch-zoom
  1. 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>
    </>
  );
}
  1. 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>
    </>
  );
}

Options

nameTypeDefault
minZoomScalenumber1.0
maxZoomScalenumber4.0
onTransform(transform: Transform) => voidundefined
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);
  },
});

How it works

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.