Search code examples
javascriptkonvajskonva

How do you detach the konva transformer from an image on "mouseout" event?


I am trying to figure out a way to detach the Konva.js transformer from my image.

I have successfully created and attached the transformer to the images using a "mouseover" event, but I can't figure out how to detach the transformer with my "mouseout" event once transformation is done. Most documentation and examples that I am finding suggest using the tr.detach() method, which I have tried with no success.

Can anyone suggest an alternate method or take a look at my code and let me know what I am missing?

Here is a link to a demo so that you can take a look at the code and see the issue that I am having: https://codesandbox.io/s/intelligent-cohen-2f38i?file=/index.html


Solution

  • Note: You might want to reconsider the use of attachTo() command. The Konva docs at konvajs.org/api/Konva.Transformer.html say about attachTo() that 'This method is deprecated and will be removed soon'.

    Transformer has the nodes[] array into which you push the shapes that you want to have the transformer attached to. In your case it sounds like you are showing the transformer on one node at a time - the array allows you to add multiple shapes which you will find useful another time. For example...

    // get
    const nodes = transformer.nodes();
    
    // set
    transformer.nodes([rect, circle]);
    

    To 'remove' a node from the transformer, you need to remove it from the transformer.nodes list. If you want to clear the transformer and you only had one shape then give it an empty array.

    transformer.nodes([]); 
    

    will do that for you.