D3.JS 为什么我增加一个节点,其它节点之间的连线就断了
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<button onclick="add()" style="float:left;">click me</button>
<script src="d3.v3.min.js"></script>
<script src="jquery.min.js"></script>
<script>
var w = 960,
h = 500,
nodes = [
{name:"001"},
{name:"002"}
],
lines = [
{source:0,target:1}
],
node;
var vis = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var force = d3.layout.force()
.nodes(nodes)
.links(lines)
.size([w, h])
.charge(-1500);
force.on("tick", function(e) {
vis.selectAll("path").attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
//更新连线坐标
line.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; });
});
$(function(){
add();
});
function add(){
// Add a new random shape.
nodes.push({
type: "circle",
size: Math.random() * 300 + 100
});
// Restart the layout.
force.start();
vis.selectAll("path")
.data(nodes)
.enter().append("path")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.attr("d", d3.svg.symbol()
.size(function(d) { return 1000; })
.type(function(d) { return "circle" }))
.style("fill", "steelblue")
.style("stroke", "white")
.style("stroke-width", "1.5px")
.call(force.drag);
line = vis.selectAll("line")
.data(lines)
.enter()
.append("line")
.style("stroke","#ccc")
.style("stroke-width",1);
};
</script>