我试图在d3图中强制移动我的节点(和链接)。节点动态添加到图形中。我已经查看了大量示例,但它们基于使用force.layout而不是forceSimulation的d3过时版本。 我尝试了很多选项和案例,没有任何工作,浏览器在svg的左上角绘制了一个圆圈。
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./index.css" type="text/css">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript" src="graph.js"></script>
</head>
<body>
<div id="graph">
<script>
var graph = new myGraph("#graph");
graph.addNode("A");
graph.addNode("B");
graph.addLink("A", "B");
</script>
</div>
</body>
</html>
graph.js
function myGraph(el) {
var graph = this.graph = {
"nodes":[{"name": "a"}],
"links":[{"source":0,"target":1}]
};
this.addNode = function (name) {
graph["nodes"].push({"name":name});
update();
}
var findNode = function (name) {
for (var i in graph["nodes"]) if (graph["nodes"][i]["name"] === name) return graph["nodes"][i];
}
this.addLink = function (source, target) {
graph["links"].push({"source":findNode(source),"target":findNode(target)});
update();
}
var vis = d3.select(el).append("svg:svg")
.attr("width", 578)
.attr("height", 300);
var nodes = vis.selectAll("circle.node")
.data(graph.nodes);
var links = vis.selectAll("line.link")
.data(graph.links);
var force = d3.forceSimulation(nodes)
.force("charge", d3.forceManyBody().strength(-10))
.force("link", d3.forceLink(links))
.force("center", d3.forceCenter());
var update = function () {
var link = vis.selectAll("line.link")
.data(graph.links);
link.enter().insert("line")
.attr("class", "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; });
link.exit().remove();
var node = vis.selectAll("circle.node")
.data(graph.nodes);
node.enter().append("circle")
.attr("class", "node")
.attr("r", 10)
.attr("x", "-8px")
.attr("y", "-8px");
node.append("text")
.attr("class", "nodetext")
.attr("dx", 12)
.attr("dy", ".25em")
.text(function(d) { return d.name });
node.exit().remove();
force.on("tick", move);
function move() {
links.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; });
nodes.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"});
};
force.restart();
}
update();
}
移动函数中应该有节点和链接变量(而不是所有节点和链接),但在这种情况下浏览器会产生错误:
d3.v4.min.js:4错误:属性转换:预期数字,&#34;翻译(undefined,undefi ...&#34;。
请帮助我,让它像它应该的那样运行!