Search code examples
reactjskonvajsreact-konva

react-konva dragBound a zoomable stage


I am trying to make an application with react-konva in which an image covers the entire stage and the stage is draggable and zoomable. So I am looking for a way to bound the drag to the edges of the image.


I looked at this demo and added a dragBoundFunc in my code but using this code I am able to dragBound my stage on the top and left edges only.

Demo: https://codesandbox.io/s/tender-chatterjee-ih31j


Solution

  • This may work:

    const { stageWidth, stageHeight, stageScale } = this.state;
    
    const x = Math.min(0, Math.max(pos.x, stageWidth * (1 - stageScale)));
    const y = Math.min(0, Math.max(pos.y, stageHeight* (1 - stageScale)));
    
    return {
          x, y
    };
    

    Also, you may need to update zoom function to call bound func.

    Demo: https://codesandbox.io/s/react-konva-dragbound-for-stage-ne71c?file=/src/Demo.jsx