【问题标题】:graph layout using angularjs使用angularjs的图形布局
【发布时间】:2017-06-15 09:11:11
【问题描述】:

我目前正在使用 AngularJS 开发一个 GUI,其中包含一个图形,其中包含它的节点和连接在一个 javascript 对象中,如下所示:

Nodes = [{'name': 'name1', x: 0, y: 0, id: 1}, {'name': 'name2', x: 0, y: 0, id: 2}, {'name': 'name3', x: 0, y: 0, id: 3}];
Connections = [{'from': 1, 'to': 2}, {'from': 1, 'to': 3}];

我需要做的是为每个节点提供 x 和 y 值。目前我正在使用简单的偏移量来避免重叠并逐个节点渲染,但我想计算每个节点的 x 和 y 值以获得正确的布局。

有没有一种算法,我给我的节点和连接,并返回一个布局(每个节点的 x,y 值),这比我的简单解决方案更好看?

我已经尝试过 D3,但我已经在使用第三方库来绘制图形并且很难集成它,因此最佳解决方案是简单地给出当前库的数据结构(节点和连接)的坐标。

【问题讨论】:

    标签: javascript angularjs d3.js


    【解决方案1】:

    D3.js Force directed layout你可以找到这样的算法。如果省略绘图代码,您最终会得到以下结果:

    var width = 100;
    var height = 100;
    var Nodes = [{'name': 'name1', x: 0, y: 0, id: 1}, {'name': 'name2', x: 0, y: 0, id: 2}, {'name': 'name3', x: 0, y: 0, id: 3}];
    var Connections = [{'source': 1, 'target': 2}, {'source': 1, 'target': 3}];
    
    var simulation = d3.forceSimulation()
        .force("link", d3.forceLink().id(function(d) { return d.id; }))
        .force("charge", d3.forceManyBody())
        .force("center", d3.forceCenter(width / 2, height / 2));
    
    simulation
        .nodes(Nodes);
    
    simulation.force("link")
        .links(Connections);
    
    console.log(Nodes, Connections);
    

    如果您现在打开控制台并检查 Nodes 变量,您将看到 x 和 y 位置已更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2011-10-17
      相关资源
      最近更新 更多