Konva shape transform sharing is simple

So you have a shape with some transforms applied – you need to apply the same transforms to another shape. How do you do that ?

It turns out that Konva gives us a simple means to accomplish the challenge. We can get the first shapes transform with the shape.getTransform() method, then with a little shimmy we can apply it to the second shape.

const transform = shape1.getTransform().copy();
transform.invert();
const attrs = transform.decompose();
shape2.setAttrs(attrs);

At line 1 we make a safe copy of shape1’s transform which is important because we’re going to manipulate the transform and we do not want to affect shape1’s transform.

At line 2 we ask our safe transform copy to invert itself.

At line 3 we ask the inverted transform to decompose itself into its component steps.

At line 4 we apply those steps to shape2.

And what you expect to happen does. In the example below there are 2 rectangles. Referring to the code above, the blue rectangle is playing the role of shape1 and the pink rectangle is shape2. Without the transform sharing process it looks like this.

After the transform sharing code is added we see the image below, in which shape2 has been translated (meaning to slide across the surface) and rotated so that its drawing position and attributes are the same as those for shape1. Notice that shape2 has not changed size – this is because there is no size-affecting transform applied to shape1, but had we set shape1’s scale then the same scaling would be applied to shape2.

Summary

I don’t have a use case for transform sharing ready to illustrate the benefits for this technique. However, I know that the underlying matrix handling etc within the compound transforms of shapes are complex and if I ever do need to be able to copy them between shapes, this technique is going to be an easy and on-hand solution compared to the horror of having to produce a reliable DIY solution.

Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: