在 konvajs 中拖动不在组中的元素选择

Drag selection of elements not in group in konvajs

KonvaJs 中有没有一种方法可以一次拖动多个元素而不对它们进行分组?

想法是:监听 dragmove 事件,为您需要移动的所有其他对象应用位置差异。

let oldX, oldY;
layer.on('dragstart', (e) => {
   oldX = e.target.x();
   oldY = e.target.y();
});
layer.on('dragmove', (e) => {
   const diffX = e.target.x() - oldX;
   const diffY = e.target.y() - oldY;

   // move everyone
   layer.children.each((child) => {
     // skip draggable circle
     if (child === e.target) {
       return;
     }
     // move other nodes
     child.x(child.x() + diffX);
     child.y(child.y() + diffY);
   });
   oldX = e.target.x();
   oldY = e.target.y();
});

演示:http://jsbin.com/babasibudi/1/edit?js,output

我在组内有组(有时也在组内有组)所以为了适应这样的设置我修改了@lavrton answer以使用递归:

let oldX, oldY;
layer.on('dragstart', (e) => {
    oldX = e.target.x();
    oldY = e.target.y();
});
layer.on('dragmove', (e) => {
    // Next line you may use any other Konva.Container instead of 'layer'
    // A group of your choosing, e.g. group.getChildren().each(...
    layer.getChildren().each((child) => {
        let recursion = (node: Konva.Node) => {
            if (node instanceof Konva.Container) {
                node.getChildren().each(recursion)
            } else {
                if (node === e.target) {
                    console.log('SKIPPED')
                    return
                }
                node.x(node.x() + diffX)
                node.y(node.y() + diffY)
            }
        }
        recursion(child)
    })           
    element = this.findByShape(groupToMove)
})