【发布时间】:2014-03-06 23:20:23
【问题描述】:
我是 javascript/d3 的初学者,遇到了一个很棒的 network visualization 我想玩玩。
我希望通过在指定时间添加链接及其关联节点来使可视化动态化。
为了让我开始,我首先尝试保持所有节点都显示,然后简单地添加出现在数据文件中的链接。
剥离 original html 文件,这是我的尝试(添加 iterateLink() 函数,并稍微调整 initializeGraph() ):
function iterateLinks() {
for ( x = 0; x < zlinkz.length; x++ ) {
setTimeout( function() {
links.push(zlinkz[x]);
restart();
}, 2000);
}
}
function initializeGraph(newGraph) {
newNodes = [];
newLinks = [];
// We need a hash to fit the link structure of D3's force-directed layout
nodeHash = {};
zlinkz = [];
for ( x = 0; x < newGraph.nodes.length; x++ ) {
newNodes.push(newGraph.nodes[x]);
nodeHash[String(newGraph.nodes[x].id)] = x;
}
for ( x = 0; x < newGraph.links.length; x++ ) {
newLinks.push({id: x, source: newGraph.nodes[nodeHash[newGraph.links[x].source]], target: newGraph.nodes[nodeHash[newGraph.links[x].target]], "cost": newGraph.links[x].cost, "weight": newGraph.links[x].invcost });
}
force = d3.layout.force()
.size([width, height])
.nodes(newNodes) // initialize with a single node
.links(newLinks)
.linkDistance(60)
.charge(-60)
.on("tick", tick);
var svg = d3.select("#viz").append("svg")
.attr("width", width)
.attr("height", height)
.attr("id", "networkViz");
svg.append("rect")
.attr("width", width)
.attr("height", height)
.attr("id","backgroundRect")
.on("mousemove", mousemove);
nodes = force.nodes();
links = force.links();
node = svg.selectAll(".node");
link = svg.selectAll(".link");
arrowhead = svg.selectAll(".link");
cursor = svg.append("circle")
.attr("transform", "translate(-100,-100)")
.attr("class", "cursor")
.attr("r", 1)
.style("opacity", 0);
restart();
iterateLinks();
}
完整的代码可以在jsfiddle找到。
尽管我使用了 iterateLinks() 函数,但该函数似乎没有遍历链接并且不显示链接。
你知道我的功能哪里出了问题,以及如何解决吗?
非常感谢任何帮助! 谢谢。
===== 编辑 =====
感谢@Barnab 和@AmeliaBR 的帮助,我对here 进行了更改,还包括动态添加节点。
【问题讨论】:
标签: javascript networking d3.js visualization force-layout