首页 > 解决方案 > 解析 Json 文件和在 d3 中设置 vx 和 vy 值时遇到问题

问题描述

我在使用 d3.json() 函数解析 json 文件并将对象添加到节点树中时遇到问题。当我尝试将它们添加到模拟中时,我收到错误“Uncaught TypeError: Cannot create property 'vx' on string”。

我曾尝试研究一些示例和类似问题,但其中大多数不使用 json 函数来获取数据。有人建议在 forceManyBody 之前添加“force('link').links(graph.links)”行,但我收到错误“无法读取未定义的属性 'links'”。

var width = window.innerWidth
var height = window.innerHeight


const svg = d3.select("svg")
            .attr("viewBox",[-width/2,-height/2,width,height]);


var linkForce = d3.forceLink().id(function(d){return d.name;});

var simulation = d3.forceSimulation()

.force('link', linkForce)
.force('charge', d3.forceManyBody().strength(-120))
.force('center', d3.forceCenter(width / 2, height / 2));

d3.json("secretSanta.json", function(error, graph) {

simulation.nodes(graph.nodes);
simulation.force('link').links(graph.links)
}

我能够使用节点和链接作为代码中的变量将 d3 的 x 和 y 坐标属性设置为数组中的元素,但是由于某种原因现在没有添加它们。不确定我是否错过了一个步骤,因为我正在解析 Json 文件。这是 json 文件:https ://raw.githubusercontent.com/gracemarod/Node-Graph/master/secretSanta.json 。

任何帮助,将不胜感激。

标签: javascriptd3.js

解决方案


推荐阅读