skip to Main Content

I’m using react-zoom-pan-pinch library for zooming on and panning on images for a project. Everything works fine, however the task requires me to zoom in on the images with single click. The library has the zoom in functionality with double click but not single click.

I tried to do accomplish this by using zoomIn method, however it only zooms in on the center, not to the mouse position. I want the exact functionality of double click for the single click. Then I tried to use the setTransform method to give custom positions to zoom in but I can’t seem to get correct positions because it still doesn’t work as expected. This is how I use it:

setTransform(e.clientX - e.target.offsetLeft, e.clientY - e.target.offsetTop, scaleValue + 1);

I should also mention the images open in a modal. I’m not sure what else I can do, any ideas?

2

Answers


  1. Chosen as BEST ANSWER

    I actually figured it out thanks to a friend. For starters for some reason I figured out that I can only get the setTransform method with negative values. So the mouse positions I found didn't work, until I turned them to negative values, then I started to get some acceptable results:

    const wrapper = document.getElementsByClassName('react-transform-wrapper')?.[0];
    const x = wrapper?.getBoundingClientRect().left;
    const y = wrapper?.getBoundingClientRect().top;
    const coordinates = {
            x: x - e.clientX,
            y: y - e.clientY,
          };
    

    These positions were still a bit off when zoomed in, so obviously it needed some calculations. I got exactly what I needed with the following:

    setTransform(
            (coordinates.x + wrapper?.clientWidth / (MAX_SCALE * 2)) * MAX_SCALE,
            (coordinates.y + wrapper?.clientHeight / (MAX_SCALE * 2)) * MAX_SCALE,
            MAX_SCALE
          );
    

    I hope this will be somewhat helpful to other people.


  2. I think you can make click as dbclick by dispatchEvent()

    const dblclickEvt = document.createEvent("MouseEvents");
    dblclickEvt.initEvent("dblclick");
    element.dispatchEvent(dblclickEvt);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search