Search code examples
konvajsreact-konvakonva

Moving a Polygon with react-kova - update the position


I use Konva embedded in React. I try to move a polygon created using a finished Line. The corner points are draggable. The approach supposed to be simple. You use the points coordinates and add the relative position. My problem is that the corner points are moved how expected. The polygon itself moves twice as fast. I suspect that the position of the framework is already calculated internally and I add the moved distance on top. If I dont do that, the corner points stay behind, what is undesired too.

The handle responsible for the position is here:

 
  handleDragMoveLine = event => {

    let i;
    const points = this.state.points;
    const init_points = this.state.init_points;
    for(i = 0; i < points.length; i++) {
      let point = points[i];
      let init_point = init_points[i];
      point[0] = parseFloat(init_point[0]) + parseFloat(event.target.x());
      point[1] = parseFloat(init_point[1]) + parseFloat(event.target.y());
      points[i] = point;
    }
    // console.log("points", points);
    this.setState({
      points: points,
      flat_points: points.concat(this.state.isFinished ? [] : this.state.curMousePos).reduce((a, b) => a.concat(b), [])
    });

  };

The complete example I modified is here: https://codesandbox.io/s/fast-star-igu4v

I appreciate every help. Thanks in advance!


Solution

  • On dragging action, Konva is changing x and y coordinates.

    As you apply x and y changes into points attribute, you have that double effect. Because (1) x and y are changes and (2) points are changed too.

    There are a lot of different ways to solve the issue.

    1. Reset x and y back to original {0, 0} value

    event.position({ x: 0, y: 0})
    

    https://codesandbox.io/s/peaceful-chebyshev-0n2vw?file=/src/App.js

    2. Save position of a line into the state

    So you will have not just points but also x and y position in your state. That way you can adjust position of anchor points by that position.

    3. Make a different nodes structure, so a line an anchors are placed inside one draggable group

    <Group draggable>
      <Line/>
      <Anchors/>
    </Group>