Cytoscape Js cose 布局为所有节点提供 0

Cytoscapejs cose layput give 0 for all nodes

我正在编写一个简单的 javascript 使用 cytoscapejs 在终端中使用 nodejs。我的目标是在给定节点和边列表以及布局的情况下获取所有节点的位置。我 运行 下面的代码:

var cytoscape = require('cytoscape');

var cy = cytoscape({

  elements: [ // list of graph elements to start with
    { // node a
      data: { id: 'a' }
    },
    { // node b
      data: { id: 'b' }
    },
    { // node b
      data: { id: 'c' }
    },
    { // node b
      data: { id: 'd' }
    },
    { // node b
      data: { id: 'e' }
    },
    { // node b
      data: { id: 'f' }
    },
    { // node b
      data: { id: 'g' }
    },
    { // node b
      data: { id: 'h' }
    },
    { // edge ab
      data: { id: 'ab', source: 'a', target: 'b' }
    },
    { // edge ab
      data: { id: 'bc', source: 'b', target: 'c' }
    },
    { // edge ab
      data: { id: 'cd', source: 'c', target: 'd' }
    },
    { // edge ab
      data: { id: 'de', source: 'd', target: 'e' }
    },
    { // edge ab
      data: { id: 'ef', source: 'e', target: 'f' }
    },
    { // edge ab
      data: { id: 'fg', source: 'f', target: 'g' }
    },
    { // edge ab
      data: { id: 'gh', source: 'g', target: 'h' }
    }
  ],

  style: [ // the stylesheet for the graph
    {
      selector: 'node',
      style: {
        'background-color': '#666',
        'label': 'data(id)'
      }
    },

    {
      selector: 'edge',
      style: {
        'width': 3,
        'line-color': '#ccc',
        'target-arrow-color': '#ccc',
        'target-arrow-shape': 'triangle'
      }
    }
  ],
  layout: {name: "cose",randomize: true}
});

cy.nodes().forEach(function(s){
    console.log(s.position().x)
    console.log(s.position().y)
});

当我看到位置的结果时,它为所有节点提供 0。如果我使用其他类型的布局,它会给出 0 以外的一些结果。如何正确使用 cose 进行布局?谢谢你。

您是 运行 一个 continuous/asynchronous 布局并期望它像 discrete/synchronous 布局一样完成。

等待布局完成。如果您想在初始化时指定布局,请使用 cy.ready(),或者最好创建一个 layout and bind to layoutstop——即 layout.on('layoutstop', () => { /* ... */ }).