HTMLGraph logo HTMLGraph

Layouts

To enable automatic node positioning using a layout algorithm, call the enableLayout method on CanvasBuilder.

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

const canvas = new CanvasBuilder(element)
  .enableLayout()
  .build();

  

As shown below, coordinates are calculated automatically and do not need to be specified explicitly when calling the addNode method.

    
const element = document.createElement('div');

canvas.addNode({
  id: "node-1",
  element: element,
  ports: [
    { id: "node-1", element: element }
  ],
});

  

The enableLayout method accepts optional configuration parameters:

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

const canvas = new CanvasBuilder(element)
  .enableLayout({
    algorithm: {
      type: "forceDirected",
      dtSec: 0.02,
      nodeCharge: 10000,
      nodeMass: 1,
      effectiveDistance: 1000,
      edgeEquilibriumLength: 300,
      edgeStiffness: 100,
      maxIterations: 100,
      convergenceDelta: 0.001,
      seed: "HTMLGraph is awesome",
    },
    applyOn: "topologyChangeTimeout"
  })
  .build();

  

Configuration Parameters

NameTypeDescriptionRequiredDefault
algorithmAlgorithmConfigSpecifies the layout algorithm to applyno{ type: "forceDirected" }
applyOnTriggerSpecifies when to apply the algorithmno"topologyChangeTimeout"

AlgorithmConfig Options

AlgorithmConfigurationExample
ForceDirectedForceDirected{ type: "forceDirected" }
CustomCustom{ type: "custom", instance: new MyAlgorithm() }

Trigger strategies

StrategyDescriptionExample
TopologyChangeTimeoutLayout is recalculated when the graph topology changes. Calculation occurs in the next macrotask, allowing intensive layout computations to run after all nodes and edges have been added."topologyChangeTimeout"
ManualLayout is recalculated when the emit method is called on the provided EventSubject instance, as shown in the example below.new EventSubject()

Manual Layout Trigger

    
import { CanvasBuilder, EventSubject } from "@html-graph/html-graph";

const element = document.getElementById('canvas');
const trigger = new EventSubject();

const canvas = new CanvasBuilder(element)
  .enableLayout({
    applyOn: trigger,
  })
  .build();

// Add all nodes and edges here

// Then trigger the layout calculation
trigger.emit();