Draggable Selection
The library does not provide draggable selection out-of-the-box, but this functionality can be implemented using the provided features:
The main idea is to handle the node drag event to update all selected nodes except for the one being dragged.
const currentSelection = new Set();
let draggingNodeCoords = null;
const canvas = new CanvasBuilder(element)
.enableUserDraggableNodes({
events: {
onNodeDragStarted: (nodeId) => {
const { x, y } = canvas.graph.getNode(nodeId);
// Saving dragging node coordinates
draggingNodeCoords = { x, y };
},
onNodeDrag: (nodeId) => {
const { x, y } = canvas.graph.getNode(nodeId);
if (currentSelection.has(nodeId)) {
const dx = x - draggingNodeCoords.x;
const dy = y - draggingNodeCoords.y;
// Updating coordinates of selected nodes which are not dragging
currentSelection.forEach((selectedNodeId) => {
if (selectedNodeId !== nodeId) {
const selectedNode = canvas.graph.getNode(selectedNodeId);
canvas.updateNode(selectedNodeId, {
x: selectedNode.x + dx,
y: selectedNode.y + dy,
});
}
});
}
// Updating dragging node coordinates
draggingNodeCoords = { x, y };
},
onNodeDragFinished: () => {
// Resetting dragging node coordinates
draggingNodeCoords = null;
},
}
})
// ...
.build();
The example below demonstrates how to combine these two features so that the user can drag multiple nodes.
Hold ctrl to activate rectangular selection.