3d-force-graph

repository·master·Indexed 27 days ago

https://github.com/vasturiano/3d-force-graph

A UI component for representing graph data structures in a 3D space using a force-directed iterative layout. Built with ThreeJS and the d3-force-3d layout engine, it provides a web component (ForceGraph3D) to visualize nodes and links with customizable styling, camera controls, and interaction callbacks. Version 1.80.0.

Tokens
2.8K
Snippets
3
Records
16
Agent score
92%

What's inside 3d-force-graph

  1. Quick start with 3d-force-graph

    master

    To use 3d-force-graph, you can import it as a module or include it via a CDN script tag. Once initialized with a DOM element, you can load your graph data using the .graphData() method.

    Using ES Modules

    import ForceGraph3D from '3d-force-graph';

    Using a Script Tag

    <script src="//cdn.jsdelivr.net/npm/3d-force-graph"></script>

    Initializing the Graph

    const myGraph = new ForceGraph3D(document.getElementById('my-element'))
      .graphData(myData);
    import ForceGraph3D from '3d-force-graph';
    
    // or using a *script* tag
    // <script src="//cdn.jsdelivr.net/npm/3d-force-graph"></script>
    
    const myGraph = new ForceGraph3D(<myDOMElement>)
      .graphData(<myData>);
  2. Style Nodes

    master

    Customize the appearance of nodes using these methods:

    • nodeRelSize([num]): Ratio of node sphere volume per value unit (default: 4).
    • nodeVal([num, str, or fn]): Accessor for node numeric value affecting volume (default: val).
    • nodeLabel([str, or fn]): Accessor for node name shown in labels (supports text, HTML, or HTMLElement).
    • nodeVisibility([boolean, str, or fn]): Accessor for visibility (default: true).
    • nodeColor([str, or fn]): Accessor for sphere color (default: color).
    • nodeAutoColorBy([str, or fn]): Automatically group colors by attribute (e.g., 'type').
    • nodeOpacity([num]): Sphere opacity between [0, 1] (default: 0.75).
    • nodeResolution([num]): Geometric resolution (segments) for smoother spheres (default: 8).
    • nodeThreeObject([Object3d, str, or fn]): Return a custom ThreeJS Object3d for the node. If falsy, uses the default sphere.
    • nodeThreeObjectExtend([bool, str, or fn]): Whether to replace (false) or extend (true) the default node when using nodeThreeObject.
    • nodePositionUpdate([fn(nodeObject, coords, node)]): Custom function for updating node positions every render iteration.
  3. Control Camera and Rendering

    master

    Manage the viewport and rendering cycle:

    • cameraPosition([{x,y,z}], [lookAt], [ms]): Move the camera to specific coordinates. Supports animation over ms duration.
    • zoomToFit([ms], [px], [nodeFilterFn]): Automatically move the camera to make all nodes visible. px is padding, nodeFilterFn allows focusing on specific nodes.
    • pauseAnimation(): Freezes the rendering cycle and user interaction to save performance.
    • resumeAnimation(): Resumes the rendering cycle and user interaction.
    • refresh(): Redraws all nodes and links.
    • postProcessingComposer(): Access the ThreeJS EffectComposer to add rendering effects.
    • lights([array]): Set the list of ThreeJS Light instances in the scene.
    • scene(): Access the internal ThreeJS Scene.
    • camera(): Access the internal ThreeJS Camera.
    • renderer(): Access the internal ThreeJS WebGLRenderer.
  4. Initialize ForceGraph3d

    master

    Create a new 3D force-directed graph by passing a DOM element and an optional configuration object to the ForceGraph3d constructor.

    Available configuration options:

    • controlType: Camera control type. Options: trackball (default), orbit, or fly.
    • rendererConfig: Object containing parameters for the ThreeJS WebGLRenderer constructor (e.g., { antialias: true, alpha: true }).
    • extraRenderers: Array of additional renderer instances (e.g., CSS3DRenderer) to include custom objects.
    new ForceGraph3d(<domElement>, { configOptions })
  5. Handle User Interactions

    master

    Register callbacks for user events:

    • onNodeClick(fn): Triggered on node left-click. Args: (node, event).
    • onNodeRightClick(fn): Triggered on node right-click. Args: (node, event).
    • onNodeHover(fn): Triggered on mouse over. Args: (node, prevNode).
    • onNodeDrag(fn): Triggered repeatedly during node drag. Args: (node, {x,y,z}).
    • onNodeDragEnd(fn): Triggered when node drag ends. Args: (node, {x,y,z}).
    • onLinkClick(fn): Triggered on link left-click. Args: (link, event).
    • onBackgroundClick(fn): Triggered on click in empty space. Args: (event).
    • enablePointerInteraction([boolean | fn]): Enables mouse tracking for hover/click/tooltips (default: true).
    • enableNodeDrag([boolean]): Enables dragging nodes (only supported on d3 engine).
  6. Style Links

    master

    Customize the appearance of links using these methods:

    • linkLabel([str, or fn]): Accessor for link name shown in labels.
    • linkVisibility([boolean, str, or fn]): Accessor for visibility (default: true).
    • linkColor([str, or fn]): Accessor for line color (default: color).
    • linkAutoColorBy([str, or fn]): Automatically group colors by attribute.
    • linkOpacity([num]): Line opacity between [0, 1] (default: 0.2).
    • linkWidth([num, str, or fn]): Line width (default: 0).
    • linkResolution([num]): Geometric resolution for smoother cylinders (default: 6).
    • linkCurvature([num, str, or fn]): Curvature radius (0 for straight, 1 for semi-circle).
    • linkCurveRotation([num, str, or fn]): Rotation along the line axis (radians).
    • linkMaterial([Material, str, or fn]): Custom ThreeJS Material (default: MeshLambertMaterial).
    • linkThreeObject([Object3d, str, or fn]): Custom ThreeJS Object3d for links.
    • linkDirectionalArrowLength([num, str, or fn]): Length of the arrow head indicating direction.
    • linkDirectionalArrowColor([str, or fn]): Color of the arrow head (default: color).
    • linkDirectionalArrowRelPos([num, str, or fn]): Longitudinal position of arrow head (0 to 1).
    • linkDirectionalParticles([num, str, or fn]): Number of particles to display along the link line.
    • linkDirectionalParticleSpeed([num, str, or fn]): Speed of directional particles (default: 0.01).
  7. Use Graph Utility Methods

    master

    Perform coordinate transformations and bounding box calculations:

    • getGraphBbox([nodeFilterFn]): Returns the current bounding box of nodes as { x: [min, max], y: [min, max], z: [min, max] }.
    • graph2ScreenCoords(x, y, z): Translates graph coordinates to viewport {x, y} coordinates.
    • screen2GraphCoords(x, y, distance): Translates viewport {x, y} and camera distance to graph {x, y, z} coordinates.
  8. Load and Configure Graph Data

    master

    Provide data to the graph using the following methods:

    • graphData([data]): Getter/setter for the graph data structure. Supports incremental updates.
    • jsonUrl([url]): URL of a JSON file to load graph data directly.

    To map data to the graph, configure these accessors:

    • nodeId([str]): Attribute for unique node IDs (default: id).
    • linkSource([str]): Attribute for the source node ID (default: source).
    • linkTarget([str]): Attribute for the target node ID (default: target).

    Input JSON Format:

    {
        "nodes": [
            {
              "id": "id1",
              "name": "name1",
              "val": 1
            }
        ],
        "links": [
            {
                "source": "id1",
                "target": "id2"
            }
        ]
    }
    {
        "nodes": [
            {
              "id": "id1",
              "name": "name1",
              "val": 1
            },
            {
              "id": "id2",
              "name": "name2",
              "val": 10
            }
        ],
        "links": [
            {
                "source": "id1",
                "target": "id2"
            }
        ]
    }
  9. Configure Force Engine

    master

    Adjust the physics simulation settings:

    • forceEngine([str]): Choose between d3 (default) or ngraph.
    • numDimensions([int]): Number of dimensions for simulation (1, 2, or 3).
    • dagMode([str]): Apply layout constraints for Directed Acyclic Graphs (e.g., td, bu, lr, rl, zout, zin, radialout, radialin).
    • d3Force(str, [fn]): Configure or add internal d3 forces (e.g., 'link', 'charge', 'center').
    • d3ReheatSimulation(): Sets alpha to 1 to restart the d3 simulation.
    • warmupTicks([int]): Number of layout cycles to run before starting to render.
    • cooldownTime([num]): How long (ms) to render before stopping and freezing the layout engine.
  10. Control Camera and Animation

    master

    Manage the view and rendering state using these methods:

    • pauseAnimation(): Pauses the graph animation.
    • resumeAnimation(): Resumes the graph animation.
    • cameraPosition(position: Partial<Coords>, lookAt?: Coords, transitionMs?: number): Sets the camera position and target.
    • zoomToFit(durationMs?: number, padding?: number, nodeFilter?: (node: N) => boolean): Zooms the camera to fit the graph or a filtered subset of nodes.
    • controls(): Returns the underlying Three.js controls object.