Search code examples
javascriptkonvajskonva

How to get width of the image with non zero rotation (konva)


I have an image inside Group element. With Transformer element, user changes image width and rotation. After that, how do I get image width? getWidth() returns the value which I manually have set while creating new Image. getClientRect().width returns the actual width, the way it displayed for the user, so it seems ok, but the problem with it starts when the image is rotated. Because the getClientRect().width returns not the image width (y), but the width of circumscribed rectangle of our image (x)
circumscribed rectangle of an image

I'm using Konva v7.0


Solution

  • See Konva code tutorial re transformers here, image below. The width and height values do not change as the shape is 'stretched', but the scale values do change.

    enter image description here

    The intro to the transformer class in the Konva docs says:

    Transformer constructor. Transformer is a special type of group that allow you transform Konva primitives and shapes. Transforming tool is not changing width and height properties of nodes when you resize them. Instead it changes scaleX and scaleY properties.

    And I have seen in the Konva docs various mentions that the dimension methods do not take into account scaling.

    In summary then, the transformer changes the dimensions of shapes it effects by scaling them. Therefore the current scaled width for a shape can be found by:

    let visibleWidth = shape.width() * shape.scaleX();
    

    If the shape in question is part of a group that is transformed then you will need to use

    let visibleWidth = shape.width() * shape.getAbsoluteScale().x;
    

    to get the absolute scale of the node which takes into account its ancestor scales.