Search code examples
reactjskonvajsreact-konva

react-konva set a shape at the center of stage


I am using react-konva for drawing shapes on a stage and to edit them I select that shape and the shape has be set to focus on stage(i.e come to the center of the stage). On the click of a button I am updating the X,Y and scale of the stage but I am not getting the shape exactly at the center of the stage.

Please see this demo and share your inputs on this:

https://codesandbox.io/s/shapecenterdemo-o9hg2?file=/src/ShapeCenterDemo.jsx

PS: Can't remove the dragBoundFunc from the stage.


Solution

  • Based on your demo:

      focusRect = () => {
        let { rect, stageWidth, stageHeight } = this.state;
    
        let newScale = 6;
        const rectWidth = 50 * newScale;
        const rectHeight = 50 * newScale;
    
      
    
        const x =  - rect.x * newScale + stageWidth / 2 - rectWidth / 2 ;
        const y =  - rect.y * newScale + stageHeight / 2 - rectHeight / 2;
    
    
        let pos = this.boundFunc({ x, y }, newScale);
    
        this.setState({
          stageX: pos.x,
          stageY: pos.y,
          stageScale: newScale
        });
      };
    

    https://codesandbox.io/s/react-konva-center-a-shape-7ttts