项目作者: littlee

项目描述 :
react hook for panning & zooming element
高级语言: JavaScript
项目地址: git://github.com/littlee/use-pan-zoom.git
创建时间: 2020-04-16T09:47:36Z
项目社区:https://github.com/littlee/use-pan-zoom

开源协议:

下载


use-pan-zoom

React hook for panning & zooming element

Install

  1. npm i -S use-pan-zoom

Usage

  1. import React from 'react';
  2. import usePanZoom from 'use-pan-zoom';
  3. const App = () => {
  4. const { elemRef, style } = usePanZoom();
  5. return (
  6. <div
  7. ref={elemRef}
  8. style={{
  9. touchAction: 'none',
  10. transformOrigin: '0 0',
  11. transform: `translate3d(${style.x}px, ${style.y}px, 0) scale(${style.scale})`
  12. }}
  13. ></div>
  14. );
  15. };

API

  1. const values = usePanZoom(options);

values: (Object)

options: (Object)

  • minScale: (Number) minimum scale, default -Infinity
  • maxScale: (Number) maximum scale, default Infinity
  • bounds: (Object: {x?: [Number, Number], y?: [Number, Number]} | Function: ({ scale }) => Object) element position bounds, default: { x: [-Infinity, Infinity], y: [-Infinity, Infinity] }
  • onPanStart: (Function(event)) pan start callback
  • onPan: (Function(event)) panning callback
  • onPanEnd: (Function(event)) pan end callback
  • onZoomStart: (Function(event)) zoom start callback
  • onZoom: (Function(event)) zooming callback
  • onZoomEnd: (Function(event)) zoom end callback

FAQ

  • multiple refs integration
  1. const App = () => {
  2. const myRef = useRef();
  3. const { elemRef } = usePanZoom();
  4. return (
  5. <div
  6. ref={node => {
  7. myRef.current = node;
  8. elemRef(node);
  9. }}
  10. />
  11. );
  12. };

Caveats

calculate bounds based on the current scale

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

  1. usePanZoom({
  2. bounds: ({ scale }) => {
  3. return {
  4. x: [parent.width - element.width * scale, 0],
  5. y: [parent.height - element.height * scale, 0]
  6. };
  7. }
  8. });