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

时间:2017-07-06 20:28:09

标签: konvajs

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

2 个答案:

答案 0 :(得分:1)

这个想法是:听取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

答案 1 :(得分:0)

我在组内有组(有时在组内也有组),为适应这种设置,我修改了@lavrton答案以使用递归:

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)
})