sasza2 / react-panzoom

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Control buttons with percentages

aysur12 opened this issue · comments

Hi, @sasza2, this is a great library!
I would like to ask about there how can I implement zoom buttons with a percentage (e.g. 50% to 100%) linked to the mouse wheel?
Thanks in advance)

hi, thanks a lot:)

please download version 1.17.0 and check this example:

import { CSSProperties, useRef, } from 'react'
import PanZoom, { API } from '@sasza/react-panzoom'

const CONTAINER_STYLES: CSSProperties = {
  border: '1px solid gray',
  height: 500,
  width: 400,
}

const ELEMENT_STYLES: CSSProperties  = {
  backgroundColor: 'violet',
  left: 0,
  position: 'absolute',
  textAlign: 'center',
  width: 400,
}

function App() {
  const panZoomRef = useRef<API>(null);

  const changeZoom = (addToCurrent: number) => {
    if (!panZoomRef.current) return

    const position = panZoomRef.current.getPosition();
    const parentNode = panZoomRef.current.childNode.parentNode as HTMLDivElement;
    const parentRect = parentNode.getBoundingClientRect();
    const currentZoom = panZoomRef.current.getZoom();

    const centerX = parentRect.width / 2
    const centerY = parentRect.height / 2

    const xOffset = (centerX - parentRect.left - position.x) / currentZoom;
    const yOffset = (centerY - parentRect.top - position.y) / currentZoom;

    panZoomRef.current.setZoom(currentZoom + addToCurrent)

    const nextZoom = panZoomRef.current.getZoom();

    panZoomRef.current.setPosition(
      centerX - parentRect.left - xOffset * nextZoom,
      centerY - parentRect.top - yOffset * nextZoom,
    )
  }

  const zoomIn = () => changeZoom(0.1)

  const zoomOut = () => changeZoom(-0.1)

  return (
    <>
      <button onClick={zoomIn}>zoom in</button>
      <button onClick={zoomOut}>zoom out</button>
      <div style={CONTAINER_STYLES}>
        <PanZoom ref={panZoomRef}>
          <div style={ELEMENT_STYLES}>
            element
          </div>
        </PanZoom>
      </div>
    </>
  )
}

export default App

I will probably extend zoomIn and zoomOut API functions with second (x) and third argument (y) like:

zoomIn(0.1, 0.5, 0.5) // zoom by 0.1 at 50% 50% (center)

Thank you so much! That's just what I needed