HTMLGraph

Rectangular Selection

To enable the built-in rectangular selection, call the enableRectangularSelection method on the CanvasBuilder instance.

    
const element = document.getElementById("canvas");

/**
 * This function verifies whether a node rectangle intersects with the selection rectangle.
 * Both parameters are of type `DOMRect`.
 */
const checkIntersection = (nodeRect, selectionRect) => {
  const isNodeRightOfSelection = nodeRect.right < selectionRect.left;
  const isNodeLeftOfSelection = nodeRect.left > selectionRect.right;
  const isNodeBottomOfSelection = nodeRect.bottom < selectionRect.top;
  const isNodeTopOfSelection = nodeRect.top > selectionRect.bottom;

  return !(
    isNodeRightOfSelection ||
    isNodeLeftOfSelection ||
    isNodeTopOfSelection ||
    isNodeBottomOfSelection
  );
}

const canvas = new CanvasBuilder(element)
  .enableRectangularSelection({
    onSelectionFinished: (selectionRect) => {
      canvas.graph.getAllNodeIds().forEach((nodeId) => {
        const { element } = canvas.graph.getNode(nodeId);
        const nodeRect = element.getBoundingClientRect();

        const selected = checkIntersection(nodeRect, selectionRect);

        element.classList.toggle("selected", selected);
      });
    },
  })
  .build();

  

Hold the ctrl key to activate rectangular selection in the demo below.

Rectangular Selection Configuration Parameters

NameTypeDescriptionRequiredDefault
rectangleElementElementVisual element to be placed inside the selection. Should have width and height of 100%.noSemi-transparent blue rectangle with a grey dashed border
onSelectionStarted() => voidFunction to call when the selection is startedno() => {}
onSelectionChange(rect: DOMRect) => voidFunction to call when the selection rectangle is updatedno() => {}
onSelectionFinished(rect: DOMRect) => voidFunction to call when the selection is finishedno() => {}
onSelectionInterrupted(rect: DOMRect) => voidFunction to call when the selection is interrupted in progress (e.g., mouse moved outside)no() => {}
mouseDownEventVerifier(event) => booleanFunction to verify whether a mouse event should initiate the selection processno(event) => event.button === 0 && event.ctrlKey
mouseUpEventVerifier(event) => booleanFunction to verify whether a mouse event should apply the selectionno(event) => event.button === 0