【发布时间】:2015-05-12 08:20:26
【问题描述】:
我仍在尝试从我的 extern json 文件加载节点和链接。当我在redraw() 函数之外执行此操作时,它可以工作。但我的目标是加载它们,然后添加其他节点并链接到svg。这就是为什么我创建了一个 redraw() 函数,它是工作的重要组成部分。我受到force example 和other example 的启发。但什么都没有出现(我没有错误)。我需要做什么 ?
我的代码:
var width = 960,
height = 500;
var selected_node = null,
selected_link = null;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("pointer-events", "all");
var visual = svg
.append('svg:g')
.append('svg:g')
.on("mousemove", mousemove)
.on("click", click);
visual.append('svg:rect')
.attr('width', width)
.attr('height', height)
.attr('fill', 'white');
var force = d3.layout.force()
.size([width, height])
.charge(-400)
.on("tick", tick);
// Future link
var drag_line = visual.append("line")
.attr("class", "drag_line")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", 0);
var nodes = force.nodes(),
links = force.links();
var node = visual.selectAll(".node"),
link = visual.selectAll(".link");
// Allows the drag actions
var drag = force.drag()
.on("dragstart", dragstart);
d3.json("graph.json", function(error, graph) {
if (error) console.log("error: " + error);
nodes = graph.nodes;
links = graph.links;
});
// Add properties to links and nodes
function tick() {
link.attr("x1", function (d) {
return d.source.x;
})
.attr("y1", function (d) {
return d.source.y;
})
.attr("x2", function (d) {
return d.target.x;
})
.attr("y2", function (d) {
return d.target.y;
});
node.attr("cx", function (d) {
return d.x;
})
.attr("cy", function (d) {
return d.y;
});
}
function dragstart(d) {
d3.select(this).classed("selected", "selected");
}
function redraw() {
console.log("redraw start");
force
.nodes(nodes)
.links(links)
link = link.data(links);
link.enter().append("line")
.attr("class", "link");
link.exit().remove();
node = node.data(nodes);
node.enter().append("circle")
.attr("class", "node")
.attr("r", 6)
.attr("fixed", true)
.call(drag);
node.exit().transition()
.attr("r", 0)
.remove();
force.start();
}
redraw();
【问题讨论】:
-
d3.json(...是异步的,因此您可以在加载 JSON 之前调用redraw();。尝试将redraw();作为回调d3.json("graph.json", function(error, graph) { ... ... redraw();});中的最后一个命令 -
非常感谢!确实,它以这种方式工作。很遗憾,我不能强制先调用一个函数,然后再调用另一个函数。
标签: javascript json d3.js force-layout