Konva – What the hell did the Transformer actually do to my shape?

So what, you grabbed a transformer handle and stretched the rectangle and now you don’t understand what gives with the width and height – they didn’t change? You can see the freekin size changed but why are the width & height the same as before? Huh ? Stop the world, I wanna get off.

Ok, lets talk about it.

A Transformer is a specialist shape in Konva that gives you resizing for free, doing all the work you would otherwise have to do yourself and probably not half as well!

The common confusion people have is what happens to the shape’s position and size attrs when it’s transformed. Lets take the case of a Konva.Rect. We give it to the transformer by adding it to the transformer’s nodes array, simple as that. Next thing we know there are 8 ‘drag handles’ at the corners and a rotation handle on the top of the rect. Now, to keep it simple, let’s think about the case where we drag the middle-right handle to the right, which increases the rect’s width.

Really ? No – there’s the confusion point. What actually happens is that the scaleX of the rect increases, but the rect.width() remains unchanged.

The same goes for dragging the bottom-right handle all the way past the top=left to ‘flip’ the rectangle. What happens here is that the rect’s scaleX & scaleY attributes first reduce then go increasingly negative – but the kicker is that width and hight remain unaltered.

What! How! Why! How can that possibly be right ? Well, Konva is a vector graphics rendering engine. With vector graphics the drawing is stored as a sequence of drawing operations: go to {x, y} apply scale {scaleX, scaleY), draw a rectangle of size {w, h}, stroke the rectangle in black, fill it in red, etc. In a vector based world, what Konva does is entirely reasonable. But to our small human brains it defies our experience of the real word. C’est la vie.

So here’s some code to play with. Its in-line commented and not sophisticated. We draw a rect, add it to a transformer, and show the position, size and scale as we transform it.

There’s another blog post here in which I provide a playground for the various Transformer attrs that you might find useful.

Summary

When stretching a shape, the transformer affects only the scaleX & scaleY properties – not the width or height properties of the shape.

Thanks for reading.

VW April 2022.

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 )

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: