Skip to content

Commit 3158645

Browse files
committed
Add bounded force layout example.
1 parent d7ae2b8 commit 3158645

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

examples/force/force-bounds.html

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<title>Force-Directed Layout</title>
5+
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?1.29.1"></script>
6+
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.geom.js?1.29.1"></script>
7+
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?1.29.1"></script>
8+
<style type="text/css">
9+
10+
circle {
11+
stroke-width: 1.5px;
12+
}
13+
14+
line {
15+
stroke: #999;
16+
}
17+
18+
</style>
19+
</head>
20+
<body>
21+
<script type="text/javascript">
22+
23+
var w = 960,
24+
h = 500,
25+
r = 6,
26+
fill = d3.scale.category20();
27+
28+
var force = d3.layout.force()
29+
.gravity(.01)
30+
.charge(-120)
31+
.linkDistance(30)
32+
.size([w, h]);
33+
34+
var svg = d3.select("body").append("svg:svg")
35+
.attr("width", w)
36+
.attr("height", h);
37+
38+
d3.json("miserables.json", function(json) {
39+
var link = svg.selectAll("line")
40+
.data(json.links)
41+
.enter().append("svg:line");
42+
43+
var node = svg.selectAll("circle")
44+
.data(json.nodes)
45+
.enter().append("svg:circle")
46+
.attr("r", r - .75)
47+
.style("fill", function(d) { return fill(d.group); })
48+
.style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
49+
.call(force.drag);
50+
51+
force
52+
.nodes(json.nodes)
53+
.links(json.links)
54+
.on("tick", tick)
55+
.start();
56+
57+
function tick() {
58+
node.attr("cx", function(d) { return d.x = Math.max(r, Math.min(w - r, d.x)); })
59+
.attr("cy", function(d) { return d.y = Math.max(r, Math.min(h - r, d.y)); });
60+
61+
link.attr("x1", function(d) { return d.source.x; })
62+
.attr("y1", function(d) { return d.source.y; })
63+
.attr("x2", function(d) { return d.target.x; })
64+
.attr("y2", function(d) { return d.target.y; });
65+
}
66+
});
67+
68+
</script>
69+
</body>
70+
</html>

0 commit comments

Comments
 (0)