如何将拖拽节点功能添加到从json文件

时间:2018-04-29 18:04:38

标签: sigma.js

我正在尝试使用sigma.js。 我有以下工作示例,我可以从磁盘加载我的JSON对象。

<script>
sigma.parsers.json( "/data/prc_network.json",
  {container: 'network-graph'},

  function(s) { //This function is passed an instance of Sigma s
    //Initialize nodes as a circle
    s.graph.nodes().forEach(function(node, i, a) {
      node.x = Math.cos(Math.PI * 2 * i / a.length);
      node.y = Math.sin(Math.PI * 2 * i / a.length);
    });
    s.refresh();
    s.startForceAtlas2();
  });
</script>

我正在查看另一个示例drag-nodes.html,其中它创建了一些随机节点,然后将它们插入到图形中,它还定义了listeners(用于拖放事件)。 你能否帮我解决一下如何在文件&#39; /data/prc_network.json'中加载上面代码的地方?以下(我想摆脱创建随机节点并使用从物理文件加载的节点)。我没有想过,但它根本不起作用。

var i,
    s,
    N = 100,
    E = 500,
    g = {
      nodes: [],
      edges: []
    };

// Generate a random graph:
for (i = 0; i < N; i++)
  g.nodes.push({
    id: 'n' + i,
    label: 'Node ' + i,
    x: Math.random(),
    y: Math.random(),
    size: Math.random(),
    color: '#666'
  });

for (i = 0; i < E; i++)
  g.edges.push({
    id: 'e' + i,
    source: 'n' + (Math.random() * N | 0),
    target: 'n' + (Math.random() * N | 0),
    size: Math.random(),
    color: '#ccc'
  });

s = new sigma({  graph: g,  container: 'graph-container'});
// Initialize the dragNodes plugin:
var dragListener = sigma.plugins.dragNodes(s, s.renderers[0]);

dragListener.bind('startdrag', function(event) {  console.log(event);});
dragListener.bind('drag', function(event) {  console.log(event);});
dragListener.bind('drop', function(event) { console.log(event);});
dragListener.bind('dragend', function(event) {console.log(event); });

1 个答案:

答案 0 :(得分:0)

我终于找到了解决方案:

<script>
var g = {
      nodes: [],
      edges: []
    };

s = new sigma({
  graph: g,
  container: 'container',
   renderer: {
    container: document.getElementById('network-graph'),
    type: 'canvas'
   }
});

sigma.parsers.json( "/data/prc_network.json",s,
  function(s) { //This function is passed an instance of Sigma s
    //Initialize nodes as a circle
    s.graph.nodes().forEach(function(node, i, a) {
      node.x = Math.cos(Math.PI * 2 * i / a.length);
      node.y = Math.sin(Math.PI * 2 * i / a.length);
    });
    s.refresh();
    s.startForceAtlas2();
  });
</script>