如何在vis-network中为节点应用多分组并实现对应样式?
实现Vis-Network多分组节点样式自定义
需求说明
存在两种人员分组维度:
- 身份分组:
teacher(教师)、student(学生) - 性别分组:
male(男性)、female(女性)
需要实现:
teacher节点用方形表示,student节点用圆点表示male节点为蓝色,female节点为粉色
代码实现
直接通过在节点数据中定义shape和color属性,结合分组维度配置即可,完整代码示例如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>Vis-Network 多分组示例</title> <script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script> <style> #network { width: 800px; height: 600px; border: 1px solid #ccc; } </style> </head> <body> <div id="network"></div> <script> // 节点数据:同时包含身份和性别分组信息 const nodes = [ { id: 1, label: "张老师", group_1: "teacher", group_a: "male", shape: "square", color: "#4285F4" }, { id: 2, label: "李同学", group_1: "student", group_a: "female", shape: "dot", color: "#EA4335" }, { id: 3, label: "王老师", group_1: "teacher", group_a: "female", shape: "square", color: "#EA4335" }, { id: 4, label: "赵同学", group_1: "student", group_a: "male", shape: "dot", color: "#4285F4" }, { id: 5, label: "刘老师", group_1: "teacher", group_a: "male", shape: "square", color: "#4285F4" } ]; // 可选:添加连线数据 const edges = [ { from: 1, to: 2 }, { from: 1, to: 4 }, { from: 3, to: 2 }, { from: 5, to: 4 } ]; // 配置网络实例 const container = document.getElementById("network"); const data = { nodes: nodes, edges: edges }; const options = { nodes: { size: 25, font: { size: 14 } } }; // 初始化网络 new vis.Network(container, data, options); </script> </body> </html>
批量处理优化
如果节点数据是从后端批量获取的,可以通过循环遍历自动设置样式,避免手动逐个配置:
// 模拟后端返回的原始节点数据 const rawNodes = [ { id: 6, label: "陈同学", group_1: "student", group_a: "female" }, { id: 7, label: "周老师", group_1: "teacher", group_a: "male" } ]; // 批量处理样式 const processedNodes = rawNodes.map(node => ({ ...node, shape: node.group_1 === "teacher" ? "square" : "dot", color: node.group_a === "male" ? "#4285F4" : "#EA4335" })); // 将processedNodes合并到原有节点数组后使用即可
内容的提问来源于stack exchange,提问作者lix joy
相关产品推荐
相关产品推荐

