【发布时间】:2014-11-15 12:14:40
【问题描述】:
我的最终目标是获得类似于this 的东西。因此我正在使用 d3js,但我是一个非常初学者。我对强制布局进行了很多尝试,但我认为我不需要任何动画,只要我可以拖动更新链接的节点即可。我已经定义了一个有效的拖动行为:
var dragListener = d3.behavior.drag()
.on("dragstart", function (d) {
dragStarted = true;
d3.event.sourceEvent.stopPropagation();
})
.on("drag", function (d) {
// update the node position
var n = d3.select(this);
n.attr("cx", d.x = d3.event.x);
n.attr("cy", d.y = d3.event.y);
update();
})
.on("dragend", function (d) {});
我的更新方法是:
function update () {
force.nodes(nodes)
.links(links);
// Update links
var l = vis.select("#linkG").selectAll("line.link")
.data(links, function (d) { return d.source.id + "-" + d.target.id; })
.enter()
.append("svg:line")
.attr("class", "link");
l.style("stroke", "#000")
.style("stroke-width", 1);
// Update nodes
var n = vis.select("#nodeG").selectAll("a")
.data (nodes, function (d) { return d.id; })
.enter()
.append("svg:a").attr("xlink:href", function (d) { return "/user/" + d.id; })
.append("svg:circle")
.attr("class", "node")
.attr("r", function (d) { return d.r; })
.style("fill", "#454545")
.style("stroke", "#e7ecef")
.style("stroke-width", 3)
.call(dragListener);
force.on("tick", function () {
nodes[0].x = WIDTH / 2;
nodes[0].y = HEIGHT / 2;
// Tried to update the link positions
l.attr("x1", function (d) { console.log(d); return d.source.x; }) // HERE
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
// Hopefully updates the node positions
n.attr("cx", function (d) { console.log(d.x); return d.x; })
.attr("cy", function (d) { return d.y; });
});
}
我已在初始化时开始强制布局。语句console.log(d) 永远不会被触发。数据都很好,在 html 中所有元素都很好。
问题是,链接没有显示或更新。有人可以帮助我获得正确的行为吗?
【问题讨论】:
-
对于初学者来说非常有野心! :)
-
好吧,我几乎尝试了整整 3 天。
-
我向你脱帽致敬!您能否在 console.log 之后在
return d.x;上设置断点? -
谢谢!我使用崇高文本,我不知道如何设置断点,但是通过控制台日志,我看到在拖动方法中
d.x是正确的,而force.on tick..中的console.log永远不会被调用。 -
您可以在 chrome f12 脚本选项卡中的行上放置一个断点。所以当您在浏览器中运行它时,您会点击它(应该点击它)
return d.source.x;
标签: javascript d3.js