如何在基于CDN的HTML中配置SigmaJS v2的ForceAtlas2布局?
解决SigmaJS v2中ForceAtlas2布局无法运行的问题
错误原因
SigmaJS v2完全重构了API,不再像v1那样将ForceAtlas2作为实例方法内置,需单独引入对应的布局算法包和Sigma适配插件。
需要添加的CDN资源
在现有script标签后补充以下两个资源:
<!-- graphology的ForceAtlas2布局算法核心包 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/graphology-layout-forceatlas2/0.10.1/graphology-layout-forceatlas2.umd.min.js"></script> <!-- Sigma与ForceAtlas2的适配插件 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/sigma.js/2.4.0/plugins/sigma.layout.forceatlas2.min.js"></script>
修改布局调用逻辑
替换原代码中sigmaInstance.startForceAtlas2()相关代码,改用Sigma v2的布局API:
// 初始化ForceAtlas2布局,可自定义参数优化效果 const layout = sigmaInstance.addLayout('forceAtlas2', { gravity: 1, scalingRatio: 100, slowDown: 10 }); // 启动布局 layout.start(); // 1秒后停止布局 setTimeout(() => { layout.stop(); }, 1000);
完整修改后的HTML代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Quick Sigma.js Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/sigma.js/2.4.0/sigma.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/graphology/0.25.4/graphology.umd.min.js"></script> <!-- 新增ForceAtlas2相关资源 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/graphology-layout-forceatlas2/0.10.1/graphology-layout-forceatlas2.umd.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/sigma.js/2.4.0/plugins/sigma.layout.forceatlas2.min.js"></script> <script src="flows.js"></script> <script src="zones.js"></script> </head> <body style="background: lightgrey"> <div id="container" style="width: 800px; height: 600px; background: white"></div> <script> const graph = new graphology.Graph({multi: true}); zones.forEach(function (c, counter) { graph.addNode(c.sys_id, { label: `${c.zone_name}`, color: c.zone_name.toLowerCase(), x: Math.random(), y: Math.random(), size: 20 }) }); flows.forEach(function (flow) { graph.addEdge(flow.source_zone, flow.destination_zone, {size: 2, label: flow.application_name}) }); const sigmaInstance = new Sigma(graph, document.getElementById("container"), {renderEdgeLabels: true} ); // 替换原布局调用代码 const layout = sigmaInstance.addLayout('forceAtlas2', { gravity: 1, scalingRatio: 100, slowDown: 10 }); layout.start(); setTimeout(() => layout.stop(), 1000); </script> </body> </html>
补充说明
- graphology-layout-forceatlas2是实现ForceAtlas2算法的核心,Sigma v2依赖graphology处理图数据,必须引入。
- sigma.layout.forceatlas2.min.js是官方适配插件,用于让Sigma实例管理布局的启停与参数配置。
- 可根据需求调整布局参数,比如
gravity(节点吸引力)、scalingRatio(缩放比例)等,优化图的展示效果。
内容的提问来源于stack exchange,提问作者mikeb
相关产品推荐
相关产品推荐

