Visual connections between UI elements are essential in modern web applications. Whether you’re building flowcharts, org charts, mind maps, or just want to highlight relationships between components, leader lines are a powerful visual tool. This post explores 10 top JavaScript libraries that make it easy to connect elements with paths, arrows, and more.
1. Leader Line
Leader Line is one of the most popular dedicated solutions for creating connecting lines between elements. It’s a lightweight and flexible JavaScript library that uses SVG to create visually appealing connections.
Key Features:
- Support for various line types: straight, arc, fluid, magnet, and grid paths
- Customizable line styles, colors, and effects
- Animation capabilities for line creation and movement
- Automatic path positioning to avoid obstacles
- Works with dynamic elements and repositioning
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// Basic usage var line = new LeaderLine( document.getElementById('start-element'), document.getElementById('end-element') ); // With options var line = new LeaderLine( document.getElementById('start-element'), document.getElementById('end-element'), { color: '#4CAF50', size: 3, startPlugSize: 2, endPlugSize: 2, path: 'fluid', startPlug: 'disc', endPlug: 'arrow2', startSocket: 'right', endSocket: 'left' } ); |
2. jsPlumb
jsPlumb is a mature, comprehensive solution for creating interactive, connected web applications. It’s been around for years and offers both a free Community Edition and a commercial Toolkit.
Key Features:
- Extensive set of connectors, endpoints, and overlay types
- Support for drag-and-drop, connection events, and interactivity
- Automatic connector path finding and adjustment
- Easy integration with frameworks like Angular, React, and Vue
- Mature documentation and extensive examples
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Initialize jsPlumb jsPlumb.ready(function() { var instance = jsPlumb.getInstance(); // Create a connection instance.connect({ source: 'element1', target: 'element2', anchor: ['Right', 'Left'], endpoint: 'Dot', connector: ['Flowchart', { cornerRadius: 5 }], paintStyle: { stroke: '#5c96bc', strokeWidth: 2 }, overlays: [ ['Arrow', { location: 1, width: 12, length: 12 }] ] }); }); |
Community Edition | Toolkit (Commercial)
3. React Flow
React Flow is a powerful library for building node-based UIs and diagrams, specifically designed for React applications. While primarily focused on node-based diagrams, it excels at creating connections between elements.
Key Features:
- React-specific implementation with hooks and components
- Responsive and interactive diagram creation
- Built-in zoom, pan, and element selection
- Customizable edge (connection) types and styles
- TypeScript support and excellent documentation
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import React from 'react'; import ReactFlow, { Background, Controls, MiniMap } from 'react-flow-renderer'; const elements = [ // Nodes { id: '1', data: { label: 'Node 1' }, position: { x: 250, y: 5 } }, { id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 } }, // Connection { id: 'e1-2', source: '1', target: '2', animated: true, type: 'smoothstep' } ]; const Flow = () => ( <div style={{ height: 500 }}> <ReactFlow elements={elements} /> </div> ); |
4. GoJS
GoJS is a comprehensive diagramming library for building interactive diagrams in JavaScript. While it’s a commercial product, it offers powerful features for creating connections between elements.
Key Features:
- Extensive diagram types and templates
- Advanced linking capabilities and routing algorithms
- Support for complex interactions and customizations
- Data binding and integration with frameworks
- Excellent performance even with large diagrams
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// Initialize diagram var diagram = new go.Diagram("myDiagramDiv"); // Define node template diagram.nodeTemplate = new go.Node("Auto") .add(new go.Shape("RoundedRectangle", { fill: "white" }) .add(new go.TextBlock({ margin: 8 }) .bind("text", "key")); // Define link template diagram.linkTemplate = new go.Link({ routing: go.Link.AvoidsNodes }) .add(new go.Shape()) .add(new go.Shape({ toArrow: "Standard" })); // Create model and data diagram.model = new go.GraphLinksModel( [ { key: "Alpha" }, { key: "Beta" } ], [ { from: "Alpha", to: "Beta" } ] ); |
5. D3.js
D3.js is a powerful data visualization library that can be used to create custom connections between elements. While not specifically designed for leader lines, its flexibility makes it a great choice for complex visualization needs.
Key Features:
- Complete control over visual representation and behavior
- SVG-based with powerful animation capabilities
- Excellent for data-driven visualizations
- Extensive community and examples
- Highly customizable line and path generation
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Create SVG container const svg = d3.select("#container") .append("svg") .attr("width", 600) .attr("height", 400); // Define path generator const linkGenerator = d3.linkHorizontal() .x(d => d.x) .y(d => d.y); // Create a path between two points svg.append("path") .attr("d", linkGenerator({ source: { x: 100, y: 100 }, target: { x: 400, y: 300 } })) .attr("fill", "none") .attr("stroke", "#000") .attr("stroke-width", 2); |
6. JointJS
JointJS is a powerful diagramming library that excels at creating interactive diagrams with connections. It offers both an open-source core library and a commercial version with additional features.
Key Features:
- Comprehensive set of built-in shapes and link types
- Support for custom elements and connections
- Interaction with elements and links through events
- Serialization and deserialization of diagrams
- Compatible with all major JavaScript frameworks
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
// Create the paper and graph var graph = new joint.dia.Graph(); var paper = new joint.dia.Paper({ el: document.getElementById('paper'), model: graph, width: 800, height: 600, gridSize: 10, background: { color: '#f8f9fa' } }); // Create elements var rect1 = new joint.shapes.standard.Rectangle({ position: { x: 100, y: 100 }, size: { width: 100, height: 40 }, attrs: { body: { fill: '#3498db' }, label: { text: 'Element 1' } } }); var rect2 = new joint.shapes.standard.Rectangle({ position: { x: 400, y: 200 }, size: { width: 100, height: 40 }, attrs: { body: { fill: '#2ecc71' }, label: { text: 'Element 2' } } }); // Create a link between elements var link = new joint.shapes.standard.Link({ source: { id: rect1.id }, target: { id: rect2.id }, attrs: { line: { stroke: '#333333', 'stroke-width': 2, targetMarker: { type: 'path', d: 'M 10 -5 0 0 10 5 Z' } } } }); // Add elements and link to the graph graph.addCells([rect1, rect2, link]); |
7. MxGraph
MxGraph is the library that powers the popular Diagrams.net (formerly Draw.io) diagramming tool. While no longer actively maintained, it remains a powerful and widely-used solution for creating complex diagrams with connections.
Key Features:
- Rich set of features for diagram creation
- Extensive link styling and customization options
- Support for complex connection routing
- Highly customizable and extensible
- Proven in production with Diagrams.net
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Create a graph instance var container = document.getElementById('graph-container'); var graph = new mxGraph(container); // Enable features graph.setConnectable(true); graph.setAllowDanglingEdges(false); // Get default parent var parent = graph.getDefaultParent(); // Begin graph update graph.getModel().beginUpdate(); try { // Create vertices var v1 = graph.insertVertex(parent, null, 'Element 1', 20, 20, 120, 60); var v2 = graph.insertVertex(parent, null, 'Element 2', 240, 150, 120, 60); // Create edge (connection) var e1 = graph.insertEdge(parent, null, '', v1, v2); } finally { // End graph update graph.getModel().endUpdate(); } |
8. Cytoscape.js
Cytoscape.js is an open-source graph theory library for visualization and analysis. It’s particularly well-suited for network graphs and relationship visualizations.
Key Features:
- Graph theory library with visualization capabilities
- Support for large graphs with many elements and connections
- Advanced layouts and algorithms for positioning
- Customizable styles for nodes and edges
- Mobile-friendly touch interactions
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// Initialize cytoscape var cy = cytoscape({ container: document.getElementById('cy'), elements: [ // Nodes { data: { id: 'a', label: 'Node A' } }, { data: { id: 'b', label: 'Node B' } }, // Edge { data: { id: 'ab', source: 'a', target: 'b', label: 'connects to' } } ], style: [ { selector: 'node', style: { 'background-color': '#666', 'label': 'data(label)' } }, { selector: 'edge', style: { 'width': 3, 'line-color': '#ccc', 'target-arrow-color': '#ccc', 'target-arrow-shape': 'triangle', 'curve-style': 'bezier', 'label': 'data(label)' } } ], layout: { name: 'grid' } }); |
9. vis-network
vis-network is part of the vis.js visualization library, specifically designed for displaying networks of nodes and edges. It’s excellent for creating interactive network diagrams with connections.
Key Features:
- Specialized for network visualizations
- Physics-based layouts and interactions
- Customizable node and edge styles
- Support for large datasets
- Clustering and hierarchical structuring
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// Create nodes and edges var nodes = new vis.DataSet([ { id: 1, label: "Node 1" }, { id: 2, label: "Node 2" } ]); var edges = new vis.DataSet([ { from: 1, to: 2, arrows: "to" } ]); // Create a network var container = document.getElementById("network"); var data = { nodes: nodes, edges: edges }; var options = { edges: { smooth: { type: 'cubicBezier', forceDirection: 'horizontal', roundness: 0.4 } }, physics: { enabled: true, repulsion: { centralGravity: 0.0, springLength: 200, springConstant: 0.05, nodeDistance: 100, damping: 0.09 } } }; var network = new vis.Network(container, data, options); |
10. Flowchart.js
Flowchart.js is a simple yet effective library for creating SVG flowcharts from textual definitions. While more specialized, it’s perfect for creating structured diagrams with connecting lines.
Key Features:
- Text-based flowchart definition
- SVG-based rendering
- Simple and intuitive syntax
- Automatic layout and connection routing
- Lightweight and easy to integrate
Usage Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Define flowchart var diagram = flowchart.parse(` st=>start: Start e=>end: End op1=>operation: Operation 1 op2=>operation: Operation 2 cond=>condition: Yes or No? st->op1->cond cond(yes)->op2->e cond(no)->op1 `); // Render to SVG diagram.drawSVG('diagram'); |
FAQ
What is Leader-line and how does it work?
How do I install and use Leader-line in my project?
1 2 3 |
npm install leader-line |
1 2 3 |
<script src="https://cdn.jsdelivr.net/npm/leader-line@1.0.7/leader-line.min.js"></script> |
1 2 3 |
new LeaderLine(startElement, endElement, options); |
What are the alternatives to Leader-line for connecting HTML elements?
- jsPlumb – Comprehensive library with many connector types and styling options
- Drawflow – Simple library for creating flow diagrams
- jQuery Connections – Lightweight solution for connecting DOM elements
- SVG.js – General SVG manipulation library that can create connectors
- React Flow – For React applications with node-based interfaces
How do I customize the appearance of connecting lines?
- Color:
123color: 'blue'
- Line size:
123size: 3
- Line style (solid, dashed):
123dash: {animation: true}
- Start/end shapes:
123startSocket: 'top', endSocket: 'bottom'
- Arrowheads:
123endPlug: 'arrow1'
How can I make connected elements draggable?
1 2 3 4 5 |
element.addEventListener('drag', function() { line.position(); }); |
1 2 3 |
jsPlumb.draggable() |
How do I handle lines when the page scrolls?
1 2 3 4 5 |
window.addEventListener('scroll', function() { line.position(); }); |
1 2 3 |
jsPlumb.repaintEverything() |
How do I integrate Leader-line with front-end frameworks like React or Angular?
1 2 3 4 5 6 7 8 9 10 11 |
const startRef = useRef(null); const endRef = useRef(null); useEffect(() => { if (startRef.current && endRef.current) { const line = new LeaderLine(startRef.current, endRef.current); return () => line.remove(); } }, []); |
Can I create multiple connection points on a single element?
1 2 3 4 5 6 |
new LeaderLine( LeaderLine.pointAnchor(element1, { x: '50%', y: 0 }), LeaderLine.pointAnchor(element2, { x: 0, y: '50%' }) ); |
1 2 3 |
jsPlumb.addEndpoint(element, { anchor: "Top" }) |
How do I implement line routing to avoid element overlaps?
1 2 3 4 5 6 7 |
new LeaderLine(element1, element2, { path: 'grid', startSocket: 'right', endSocket: 'left' }); |
What’s the performance difference between these libraries?
- Leader-line: Lightweight with good performance for up to 100 connections
- jsPlumb: More feature-rich but heavier, optimized for complex diagrams
- jQuery Connections: Simple and lightweight but with fewer features
- SVG.js approaches: Can be highly optimized but require more manual implementation
How can I add labels or data to connecting lines?
1 2 3 4 |
const line = new LeaderLine(element1, element2); line.setMiddleLabel('Connection Label'); |
1 2 3 4 5 6 7 8 9 |
jsPlumb.connect({ source: element1, target: element2, overlays: [ ["Label", { label: "connection label", location: 0.5 }] ] }); |
Are these libraries responsive for mobile devices?
- Update positions on window resize events
- Consider touch events for interactive elements
- Adjust line sizes and styling for smaller screens
1 2 3 4 5 |
window.addEventListener('resize', function() { line.position(); }); |
Thoughts
Whether you need simple leader lines to connect UI elements or complex interactive diagrams, these JavaScript libraries offer a range of solutions to fit your specific needs. From the dedicated Leader Line library for simple connections to comprehensive diagramming tools like GoJS and JointJS, you can find the right tool for your project requirements.
When choosing a library, consider factors like:
- Framework compatibility (React, Angular, Vue, etc.)
- Performance with large numbers of connections
- Customization and styling options
- Learning curve and documentation
- Commercial vs. open-source licensing
By leveraging these libraries, you can create visually appealing and interactive connections between elements in your web applications, enhancing user experience and information clarity.
Happy connecting!