Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为新节点生成NaN坐标的力模拟_Javascript_D3.js_Visualization - Fatal编程技术网

Javascript 为新节点生成NaN坐标的力模拟

Javascript 为新节点生成NaN坐标的力模拟,javascript,d3.js,visualization,Javascript,D3.js,Visualization,我是D3.js框架的新手,正在寻求帮助。我试图用一个简单的力模拟画一个网络。我希望每秒添加一个新节点并加入模拟 下面是我的尝试。我用两个节点启动sim卡,它们表现得很好。但是,当我添加第三个节点时,模拟会将NaN值指定给它的x和y坐标 HTML: 您必须将阵列传递给模拟 simulation.nodes(nodes); 。。。在重画功能中 以下是仅包含该更改的代码: const svg=d3.select('svg'); 常量高度=+svg.attr('height'); 常量宽度=+svg

我是D3.js框架的新手,正在寻求帮助。我试图用一个简单的力模拟画一个网络。我希望每秒添加一个新节点并加入模拟

下面是我的尝试。我用两个节点启动sim卡,它们表现得很好。但是,当我添加第三个节点时,模拟会将NaN值指定给它的x和y坐标

HTML:


您必须将阵列传递给模拟

simulation.nodes(nodes);
。。。在
重画功能中

以下是仅包含该更改的代码:

const svg=d3.select('svg');
常量高度=+svg.attr('height');
常量宽度=+svg.attr('width');
//测试数据
常量节点=[{},{}];
设置超时(()=>{
nodes.push({});
重画();
}, 2000);
常量勾选=()=>{
svg.selectAll('g.node')
.attr('transform',d=>{
if(isNaN(d.x)| isNaN(d.y)){
console.error('nan!!!');
d、 x=50;
d、 y=50;
}
返回`translate(${d.x},${d.y})`;
});
};
常量模拟=d3.forceSimulation()
.力('斥力',d3.力肌体().强度(-30))
.force('pin_y_至_中心',d3.force().y(d=>高度/2)。强度(0.1))
力('pin_x_至_中心',d3.forceX().x(d=>宽度/2)。强度(0.1));
模拟。on('tick',ticked);
常数重绘=()=>{
模拟。节点(节点);
const node=svg
.selectAll(“.node”)
.数据(节点)
.enter().append('g');
attr('class','node')
.append('圆')
.attr('r',5);
};
重画()

const svg = d3.select('svg');
const height = +svg.attr('height');
const width = +svg.attr('width');

// Test Data
const nodes = [ {}, {} ];

setTimeout(() => {
  nodes.push({});
  redraw();
}, 2000);

const ticked = () => {
  svg.selectAll('g.node')
    .attr('transform', d => {
      if (isNaN(d.x) || isNaN(d.y)) {
        console.error('nan!!!');
        d.x = 50;
        d.y = 50;
      }

      return `translate(${d.x},${d.y})`;
    });
};

const simulation = d3.forceSimulation()
  .force('repulsion', d3.forceManyBody().strength(-30))
  .force('pin_y_to_center', d3.forceY().y(d => height / 2).strength(0.1))
  .force('pin_x_to_center', d3.forceX().x(d => width / 2).strength(0.1));

simulation.nodes(nodes);
simulation.on('tick', ticked);

const redraw = () => {
  const node = svg
    .selectAll('.node')
    .data(nodes)
    .enter().append('g');

  node.attr('class', 'node')
    .append('circle')
      .attr('r', 5);
};

redraw();
simulation.nodes(nodes);