force-graph

repository·master·Indexed 24 days ago

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

A high-performance web component for rendering 2D force-directed graphs on an HTML5 canvas. It uses d3-force for physics and supports interactive features including zooming, panning, node dragging, and custom canvas rendering for nodes and links. Version 1.51.4.

Tokens
3.3K
Snippets
3
Records
16
Agent score
85%

What's inside force-graph

  1. Overview of force-graph

    master

    force-graph is a web component for representing graph data structures in a 2-dimensional canvas using a force-directed iterative layout. It uses HTML5 canvas for rendering and d3-force as the underlying physics engine.

    Key features include:

    • Canvas zooming and panning.
    • Node dragging.
    • Node and link hover/click interactions.
    • High performance rendering suitable for medium to large graphs.

    For 3D visualizations, use 3d-force-graph. For React applications, use react-force-graph.

  2. Quick start with force-graph

    master

    To use force-graph, you can import it as an ES module or include it via a CDN script tag. Once initialized, you create a new instance by passing a DOM element and then populate it with data using the .graphData() method.

    Using ES Modules:

    import ForceGraph from 'force-graph';

    Using a Script Tag:

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

    Initialization:

    const myGraph = new ForceGraph(document.getElementById('my-element'))
      .graphData(myData);
  3. Custom Canvas Rendering

    master

    For advanced visualizations, you can provide custom rendering functions that interact directly with the Canvas 2D API.

    Node Custom Rendering:

    • nodeCanvasObject(renderFn): A function (obj, canvasContext, globalScale) => void to draw custom node shapes.
    • nodePointerAreaPaint(renderFn): A function (obj, paintColor, canvasContext, globalScale) => void to define the interactive area around a node.
    • nodeCanvasObjectMode(modeAccessor): Determines if the custom object should replace, be drawn before, or be drawn after the default node.

    Link Custom Rendering:

    • linkCanvasObject(renderFn): A function (obj, canvasContext, globalScale) => void to draw custom link shapes.
    • linkDirectionalParticleCanvasObject(renderFn): A function (x, y, link, canvasContext, globalScale) => void to customize the appearance of moving particles on links.
  4. Control rendering and viewport

    master

    Manage the canvas display, zoom, and pan behavior.

    Container Layout

    • width([px]) / height([px]): Set canvas dimensions.
    • backgroundColor([str]): Set chart background color.

    Render Control

    • autoPauseRedraw([boolean]): Automatically pause redrawing when simulation is halted (Default: true).
    • pauseAnimation() / resumeAnimation(): Freeze or resume the rendering cycle.
    • centerAt([x], [y], [ms]): Programmatically pan the center of the viewport.
    • zoom([num], [ms]): Programmatically set the zoom level.
    • zoomToFit([ms], [px], [nodeFilterFn]): Zoom/pan to fit all nodes within the canvas.
    • minZoom([num]) / maxZoom([num]): Set zoom limits.
    • onRenderFramePre(fn) / onRenderFramePost(fn): Callbacks invoked before/after every frame. Signature: (canvasContext, globalScale).

    Coordinate Utilities

    • getGraphBbox([nodeFilterFn]): Returns the bounding box of nodes as { x: [min, max], y: [min, max] }.
    • screen2GraphCoords(x, y): Translates screen coordinates to graph domain.
    • graph2ScreenCoords(x, y): Translates graph coordinates to screen viewport.
  5. Handle user interactions and events

    master

    Register callbacks for mouse and touch interactions.

    Node Events

    • onNodeClick(node, event)
    • onNodeRightClick(node, event)
    • onNodeHover(node, prevNode)
    • onNodeDrag(node, {x, y}): Invoked repeatedly during drag.
    • onNodeDragEnd(node, {x, y}): Invoked when node is released.
    • onLinkClick(link, event)
    • onLinkRightClick(link, event)
    • onLinkHover(link, prevLink)

    Global/Background Events

    • onBackgroundClick(event)
    • onBackgroundRightClick(event)
    • onZoom({ k, x, y }) / onZoomEnd({ k, x, y }): Zoom/pan event callbacks.

    Interaction Settings

    • enableNodeDrag([boolean]): Enable/disable node dragging.
    • enableZoomInteraction([boolean|fn]): Enable/disable zoom.
    • enablePanInteraction([boolean|fn]): Enable/disable panning.
    • enablePointerInteraction([boolean]): Enables mouse tracking for hover/click/drag. Note: Disabling this improves performance.
    • showPointerCursor([boolean|fn]): Show pointer cursor on hoverable elements.
  6. Style links in the force graph

    master

    Customize the appearance and behavior of links using these methods.

    • linkLabel([str, fn]): Accessor for the link name (shown in label).
    • linkVisibility([boolean, str, fn]): Determines if the link line is rendered.
    • linkColor([str, fn]): Accessor for line color.
    • linkAutoColorBy([str, fn]): Automatically groups colors by an attribute.
    • linkLineDash([num[], str, fn]): Determines if a line dash is applied (e.g., [5, 15]).
    • linkWidth([num, str, fn]): Accessor for line width.
    • linkCurvature([num, str, fn]): Curvature radius (0 is straight, 1 is semi-circle). Positive is clockwise, negative is counter-clockwise.
    • linkCanvasObject([fn]): Custom drawing callback. Signature: .linkCanvasObject(link, canvasContext, currentGlobalScale).
    • linkCanvasObjectMode([str, fn]): Drawing mode: 'replace', 'before', or 'after'.
    • linkDirectionalArrowLength([num, str, fn]): Length of the arrow head in px.
    • linkDirectionalArrowColor([str, fn]): Color of the arrow head.
    • linkDirectionalArrowRelPos([num, str, fn]): Longitudinal position of arrow (0 to 1).
    • linkDirectionalParticles([num, str, fn]): Number of moving particles along the link.
    • linkDirectionalParticleSpeed([num, str, fn]): Speed of particles (ratio of link length per frame).
    • linkDirectionalParticleOffset([num, str, fn]): Initial position offset (0 to 1).
    • linkDirectionalParticleWidth([num, str, fn]): Diameter of particles.
    • linkDirectionalParticleColor([str, fn]): Color of particles.
    • linkDirectionalParticleCanvasObject([fn]): Custom particle drawing. Signature: .linkDirectionalParticleCanvasObject(x, y, link, canvasContext, currentGlobalScale).
    • emitParticle(link): Emits a single non-cyclical particle within a specific link.
  7. Configure the d3-force engine

    master

    Directly configure the underlying d3-force simulation.

    DAG (Directed Acyclic Graph) Layout

    Use these when your graph has a specific directionality and no cycles.

    • dagMode([str]): Set layout direction: 'td' (top-down), 'bu' (bottom-up), 'lr' (left-to-right), 'rl' (right-to-left), 'radialout', or 'radialin'.
    • dagLevelDistance([num]): Distance between graph depths.
    • dagNodeFilter([fn]): Specify nodes to ignore in DAG processing.
    • onDagError([fn]): Callback for when a cycle is encountered (Default: throws exception).

    Simulation Parameters

    • d3AlphaMin([num]): Simulation alpha min.
    • d3AlphaDecay([num]): Simulation intensity decay.
    • d3VelocityDecay([num]): Node velocity decay (medium resistance).
    • d3Force(str, [fn]): Configure or add internal forces (e.g., 'link', 'charge', 'center').
    • d3ReheatSimulation(): Sets alpha to 1 to restart simulation.
    • warmupTicks([int]): Number of dry-run cycles before rendering.
    • cooldownTicks([int]): Number of frames to render before freezing.
    • cooldownTime([num]): Time in ms to render before freezing.
    • onEngineTick(fn) / onEngineStop(fn): Callbacks for simulation lifecycle.
  8. Style nodes in the force graph

    master

    Customize the appearance and behavior of nodes using these methods. Most accept a string (attribute name), a function fn(node), or a constant.

    • nodeRelSize([num]): Ratio of node circle area per value unit (Default: 4).
    • nodeVal([num, str, fn]): Accessor for the node's numeric value (affects area).
    • nodeLabel([str, fn]): Accessor for the name shown in labels (supports text, HTML, or HTMLElement).
    • nodeVisibility([boolean, str, fn]): Determines if a node is displayed.
    • nodeColor([str, fn]): Accessor for node color.
    • nodeAutoColorBy([str, fn]): Automatically groups colors by an attribute (e.g., 'type') for nodes without a specific color.
    • nodeCanvasObject([fn]): Custom drawing callback. Signature: .nodeCanvasObject(node, canvasContext, currentGlobalScale).
    • nodeCanvasObjectMode([str, fn]): Specifies how custom drawing interacts with default drawing. Values: 'replace', 'before', or 'after'.
  9. Configure data input and accessors

    master

    Use the following methods to define how the graph reads your data structure. The default data format expects a nodes array and a links array. You can customize which attributes in your objects are used as unique identifiers or connection points.

    • graphData([data]): Getter/setter for the graph data structure. Supports incremental updates.
    • nodeId([str]): Accessor for the unique node ID (used by links).
    • linkSource([str]): Accessor for the link's source node ID.
    • linkTarget([str]): Accessor for the link's target node ID.
    {
        "nodes": [
            {
              "id": "id1",
              "name": "name1",
              "val": 1
            },
            {
              "id": "id2",
              "name": "name2",
              "val": 10
            }
        ],
        "links": [
            {
                "source": "id1",
                "target": "id2"
            }
        ]
    }
  10. Import the force-graph library

    master
    The force-graph package can be imported directly. The default export is the main ForceGraph class/functionality. Note that the library also imports its own CSS, so importing the package should include the necessary styles for the graph components.
  11. Style Nodes and Links

    master

    The API provides extensive methods to style the visual representation of nodes and links using accessors (value, string, or function).

    Node Styling:

    • nodeRelSize(size): Relative size of nodes.
    • nodeVal(accessor): Value used for node sizing.
    • nodeLabel(accessor): Label text (string or HTMLElement).
    • nodeVisibility(accessor): Boolean visibility.
    • nodeColor(accessor): Color string.
    • nodeAutoColorBy(accessor): Automatically assigns colors based on a property.
    • nodeCanvasObject(renderFn): Custom canvas rendering for nodes.
    • nodePointerAreaPaint(renderFn): Custom painting for the pointer interaction area.

    Link Styling:

    • linkLabel(accessor): Label text.
    • linkVisibility(accessor): Boolean visibility.
    • linkColor(accessor): Color string.
    • linkWidth(accessor): Line width.
    • linkCurvature(accessor): Curvature of the link.
    • linkLineDash(accessor): Array of numbers for dashed lines.
    • linkDirectionalArrowLength(accessor): Length of the arrow head.
    • linkDirectionalArrowColor(accessor): Color of the arrow head.
    • linkDirectionalParticles(accessor): Number of moving particles on the link.
    • linkDirectionalParticleSpeed(accessor): Speed of particles.
    • linkDirectionalParticleColor(accessor): Color of particles.
  12. Control Render and Animation

    master

    Manage how the graph is displayed and how it animates:

    • pauseAnimation() / resumeAnimation(): Control the simulation playback.
    • zoom(scale, durationMs): Set the zoom level.
    • zoomToFit(durationMs, padding, nodeFilter): Automatically zoom to fit all nodes (or a filtered subset) in view.
    • centerAt(x, y, durationMs): Center the view on specific coordinates.
    • autoPauseRedraw(enable): Enable/disable automatic redrawing.
    • onRenderFramePre(callback) / onRenderFramePost(callback): Execute logic before or after each frame is rendered.