<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Force Layout Example 1</title>
<style>
.node {
fill: #ccc;
stroke: #fff;
stroke-width: 2px;
}
.link {
stroke: #777;
stroke-width: 2px;
}
.line {
stroke: #777;
stroke-width: 2px;
}
</style>
</head>
<body>
<script src='http://d3js.org/d3.v3.min.js'></script>
<script>
var width = 640,
height = 480;
var nodes = [
{ "x": 200, "y": 200 },
{ "x": 500, "y": 300 },
{ "x": 500, "y": 100 },
//{ "x": 650, "y": 100 },
];
//var nodes = [
// { "x": 200, "y": 200 },
// { "x": 500, "y": 300 },
//{ "x": 500, "y": 100 },
//];
//var links = [
// { source: 0, target: 1 },
// { source: 1, target: 2 },
//];
var links = [
{ source: 0, target: 1 },
{ source: 0, target: 2 },
//{ source: 1, target: 3 },
];
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links);
force.linkDistance(75);
var link = svg.selectAll('.link')
.data(links)
.enter().append('line')
.attr('class', 'link');
var node = svg.selectAll('.node')
.data(nodes)
.enter().append('rect')
.attr('class', 'node');
var subnode = svg.selectAll('.subnode')
.data(nodes)
.enter().append('circle')
.attr('class', 'subnode');
var subnode2 = svg.selectAll('.subnode2')
.data(nodes)
.enter().append('circle')
.attr('class', 'subnode2');
force.on('end', function() {
node.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.attr("width", 50)
.attr("height", 20);
subnode.attr('r', width/250)
.attr('cx', function(d) { return (d.x); })
.attr('cy', function(d) { return d.y + 10; });
subnode2.attr('r', width/250)
.attr('cx', function(d) { return d.x+50; })
.attr('cy', function(d) { return d.y + 10; });
link.attr('x1', function(d) { return d.source.x; })
.attr('y1', function(d) { return d.source.y+ 10; })
.attr('x2', function(d) { return d.target.x+50; })
.attr('y2', function(d) { return d.target.y+ 10; });
});
force.start();
var line;
function mousedown() {
var m = d3.mouse(this);
//alert(m[0]+"---"+m[1]);
line = svg.append("line")
.attr('x1', m[0])
.attr('y1', m[1])
.attr('x2', m[0])
.attr('y2', m[1]);
svg.on("mousemove", mousemove);
}
function mousemove() {
var m = d3.mouse(this);
line.attr('x2', m[0])
.attr('y2', m[1]);
}
function mouseup() {
svg.on("mousemove", null);
}
</script>
</body>
</html>
上述解决方案会产生以下结果:
问题是我不明白为什么图是反向绘制的,而且在上面的代码中,我已经注释掉了一些节点和链接,如果您取消对它们的注释,则会有更多混乱,整个节点将以完全随机的顺序绘制,即增加更多节点和链接会导致更多混乱。
请查看JSBIN:http://jsbin.com/yuyolof/edit?html