简体   繁体   中英

KonvaJS: how to keep the position and rotation of the shape in the group after detached?

How can keep the position and rotation and scale properties of shapes in the group after detached?

It looks shapes are lost there changed properties if detach every shapes in the group after the user move or resize, rotate the group that wrapped under the Transformer.

I try it like following source.

    <button id="ungroup">ungroup</button>
    <div id="container"></div>
    const stage = new Konva.Stage({
       container: 'container',
       width: window.innerWidth,
       height: window.innerHeight
    });

    const layer = new Konva.Layer();
    stage.add(layer);

    const rect = new Konva.Rect({
       x : 50, y : 50, width: 100, height: 100,
       fill: 'black',
    });
    const rect2 = new Konva.Rect({
       x : 150, y : 50, width: 80, height: 80,
       fill: 'red',
    });

    const group = new Konva.Group({
        draggable: true
    });
    group.add(rect);
    group.add(rect2);

    const tr = new Konva.Transformer({
        node: group
    });

    layer.add(group);
    layer.add(tr);
    layer.draw();

    document.getElementById('ungroup').addEventListener('click', () => {
        tr.remove()
      // how can keep the moved or rotated properties?
      rect.moveTo(layer);
      rect2.moveTo(layer);
        group.removeChildren();
      group.remove();
      layer.draw();
    });

A group has two rectangle can move with a transformer. But after detach them, they lose movement and scale and rotation.

You can take the absolute transformation matrix of the node and after detaching, it reapply to the node.

const transform = node.getAbsoluteTransform();
const attrs = transform.decompose();
node.moveTo(layer);
node.setAttrs(attrs);

Demo: https://codepen.io/elscorpio/pen/VqvLpG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM