Search code examples
javascriptreactjsrotationscalekonvajs

Konva-JS: how do you get the updated vertices coordinates for custom shape after translation, scale or rotation?


I'm using React-Konva (React version of KonvaJS) to draw custom shapes, mostly irregular polygons, and apply transformations to it, like moving them around, scaling and rotating.

Now, once the polygons are in place I need the coordinate of the vertices for another feature, but even though I move it around and transform and whatnot, the shape appears correctly modified but the vertices coordinates are still the initial ones.

For instance if I have a triangle at (0,0), (1,0), (0.5,2) and then drag it all the way to the right, after the drag ended the triangle will appear in the new position on the canva, but when printing the vertices it still will output (0,0), (1,0), (0.5,2).

How do you get the updated coordinates of all the vertices? I'm using the Shape class for the polygons with draggable set to true for the translation, and the Transformer class for scaling and rotating.


Solution

  • Canvas, and therefore Konva which is a wrapper & enhancer of canvas functionality, uses vector graphics. An important part of vector graphics is the concept of 'transform'-ing your shapes when you rotate or scale them. Essentially, the shape will tell you its position is unchanged when rotated or scaled, but the important fact is it's transform which is what does the rotation and scaling.

    Long story short, without needing to understand the matrix math, you can 'get' the transform that is applied to your shape and give it the x,y positions of your shape's vertices/corners, and it will return the x,y of that point with the transform applied.

    Here is an earlier answer to the same question but regarding rectangles. https://stackoverflow.com/a/65645262/7073944

    This is vanilla JS but hopefully you can react-ify it.

    The critical functions are node.getTransform and its close relation node.getAbsoluteTransform methods will retrieve the transform applied to the node (shape).