我刚刚开始使用 d3.js,无法让简单的演示正常工作。 调试起来很困难:如果存在错误,它通常会在 d3 的精简代码中崩溃,并且没有堆栈跟踪。在这种情况下,它根本不会将任何错误打印到错误控制台。
当我运行此代码时,我的所有节点都卡在位置 (0,0),而不是通过 force() 进行布局。怎么了?
<html>
<meta charset="UTF-8">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
$(function() {
var svg = d3.select('#graph').append('svg').attr('width', 900).attr('height', 900)
var myNodes = [{name:'a'}, {name:'b'}, {name:'c'}]
var myLinks = [{source:myNodes[0], target:myNodes[1]}, {source:myNodes[1], target:myNodes[2]}, {source:myNodes[2], target:myNodes[0]}]
svg.append("text").text("myNodes[0].name=" + myNodes[0].name).attr('y', 50)
var force = d3.layout.force().charge(-120).linkDistance(30).size([900, 900])
var link = svg.selectAll("line")
.data(myLinks)
.enter().append("svg:line");
var node = svg.selectAll("circle")
.data(myNodes)
.enter().append("svg:circle")
.attr("r", 6)
.call(force.drag)
force.nodes(myNodes).links(myLinks).start()
});
</script>
</head>
<body>
<div id="graph"></div>
</body>
</html>
最佳答案
Force 只是处理 setting x/y attributes on the nodes and links :
... The initial x and y coordinates, if not already set externally to a valid number, are computed by examining neighboring node..
它实际上并不处理相应 svg 形状的更新。您通常会在 tick event 中执行此操作:
Listen to tick events to update the displayed positions of nodes
force.on("tick", function() {
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; });
});
您的示例中唯一缺少的其他部分是设置线条的样式。默认情况下,它们没有描边颜色,因此看起来不可见。您可以直接在线上设置颜色,如下所示:
var link = svg.selectAll("line")
.data(myLinks)
.enter().append("svg:line")
.attr('stroke', 'red')
.attr('stroke-width', 2)
或者为它们创建一个 CSS 类:
<style>
.link {
stroke: blue;
stroke-width: 1.5px;
}
</style>
并在创建它们时用它标记它们:
var link = svg.selectAll("line")
.data(myLinks)
.enter().append("svg:line")
.attr('class', 'link')
关于d3.js 强制布局不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17695830/