Skip to content

Instantly share code, notes, and snippets.

@hsuh
Last active August 29, 2015 14:01
Show Gist options
  • Save hsuh/2ad176b6912a43afebfc to your computer and use it in GitHub Desktop.
Save hsuh/2ad176b6912a43afebfc to your computer and use it in GitHub Desktop.
Force layout constrained
var width= 960; var height = 500;
var color = d3.scale.category20();
var cola = cola.d3adaptor()
.linkDistance(120)
.avoidOverlaps(true)
.size([width,height])
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("graph_data.json", function(error, graph) {
cola.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("rect")
.attr("class", "node")
.attr("width", function (d) { return d.width; })
.attr("height", function (d) { return d.height; })
.attr("rx", 5).attr("ry", 5)
.style("fill", function (d) { return color(1); })
.call(cola.drag);
var label = svg.selectAll(".label")
.data(graph.nodes)
.enter().append("text")
.attr("class", "label")
.text(function (d) { return d.name; })
.call(cola.drag);
node.append("title")
.text(function (d) { return d.name; });
cola.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("x", function (d) { return d.x - d.width / 2; })
.attr("y", function (d) { return d.y - d.height / 2; });
label.attr("x", function (d) { return d.x; })
.attr("y", function (d) {
var h = this.getBBox().height;
return d.y + h/4;
});
});
});
{
"nodes":[
{"name":"a","width":60,"height":40},
{"name":"b","width":60,"height":40},
{"name":"c","width":60,"height":40},
{"name":"d","width":60,"height":40},
{"name":"e","width":60,"height":40}
],
"links":[
{"source":0,"target":1},
{"source":1,"target":2},
{"source":2,"target":0},
{"source":2,"target":3}
]
}
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://marvl.infotech.monash.edu/webcola/cola.v2.min.js"></script>
</head>
<body>
<h1> Force layout constrained </h1>
<script src="d3cola.js"></script>
</body>
</html>
.node {
stroke: #fff;
stroke-width: 1.5px;
cursor: move;
}
.link {
stroke: #999;
stroke-width: 3px;
stroke-opacity: 1;
}
.label {
fill: white;
font-family: Verdana;
font-size: 25px;
text-anchor: middle;
cursor: move;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment