如何在VisJS Network中实现单向边并调整指定节点至三角形左侧?
Let me walk you through fixing both of your Vis.js network problems based on my hands-on experience with the library:
1. Force All Edges to Be Unidirectional (Forward)
By default, Vis.js edges don’t display arrows unless explicitly configured. To ensure every edge is a one-way forward arrow, follow these steps:
- Set global edge defaults: When initializing your network, define a default
arrowsproperty for edges to maintain consistency across all connections. This saves you from configuring each edge individually.const options = { edges: { arrows: { to: { enabled: true, type: 'arrow' } // Enables forward-facing arrow for all edges }, // Add other edge styles (color, width, etc.) as needed }, hierarchical: { direction: 'LR', // Maintain horizontal left-to-right layout sortMethod: 'directed' // Ensures layout follows the direction of your edges } // Other network configuration options... }; - Validate edge data: Double-check your Dataset edge entries to ensure you aren’t accidentally including reverse edges (e.g., from a child node back to its parent). Remove or reorient any such edges to match your desired forward flow.
2. Position Nodes B, C, F on the Left Side of the Hierarchy
For horizontal left-to-right hierarchical layouts, nodes are placed based on their hierarchical level. To lock B, C, F to the leftmost side, explicitly set their level property in the node data:
- Assign fixed levels to target nodes: When defining your nodes in the Dataset, add a
levelfield to B, C, F and set it to0(the lowest possible level, which places nodes on the far left). Other nodes can inherit levels automatically or have higher levels assigned as needed.const nodes = new vis.DataSet([ { id: 'A', label: 'A', level: 1 }, { id: 'B', label: 'B', level: 0 }, // Lock to leftmost level { id: 'C', label: 'C', level: 0 }, { id: 'F', label: 'F', level: 0 }, { id: 'D', label: 'D', level: 2 }, // Add remaining nodes... ]); - Tweak hierarchical layout settings: Ensure your configuration respects manual levels by adjusting spacing and disabling parent centralization if needed. Here’s an updated options snippet:
const options = { hierarchical: { direction: 'LR', sortMethod: 'directed', levelSeparation: 150, // Space between horizontal levels nodeSpacing: 100, // Space between nodes in the same level parentCentralization: false // Prevents parent nodes from shifting to the center }, // Keep the edge arrow settings from earlier... };
If manual levels don’t work as expected, you can experiment with the sortMethod (try 'hubsize' for node-size-based sorting) or write a custom sort function, but explicit level assignment is the most reliable way to lock nodes into specific positions.
内容的提问来源于stack exchange,提问作者Krishna

