Reputation: 4494
Is there a way in KonvaJs for dragging multiple elements at once without grouping them ?
Upvotes: 1
Views: 1731
Reputation: 8251
I had groups inside groups (and sometimes groups inside those as well) so to fit such setup I modified @lavrton answer to use recursion:
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)
})
Upvotes: 0
Reputation: 20373
The idea is: listen to dragmove
event, apply position diff for all other objects that you need to move.
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();
});
Demo: http://jsbin.com/babasibudi/1/edit?js,output
Upvotes: 2