Skip to content

Instantly share code, notes, and snippets.

@erkal
Last active August 29, 2015 13:57
Show Gist options
  • Save erkal/9746488 to your computer and use it in GitHub Desktop.
Save erkal/9746488 to your computer and use it in GitHub Desktop.
Basic Force Layout

Basic Force Layout

Serves as a basis for other force layout examples.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.link {
stroke: black;
stroke-width: 2px;
}
.node {
fill: steelblue;
stroke: white;
stroke-width: 2px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 960,
height = 500,
nodes = [{},{},{}],
links = [{source: 0, target: 1}, {source: 1, target: 2}, {source: 2, target: 0}];
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links)
.linkDistance(150)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svgLinks = svg.selectAll(".link").data(links)
.enter().append("line")
.attr("class", "link");
svgNodes = svg.selectAll(".node").data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 8)
.call(force.drag);
function tick() {
svgNodes
.attr("cx", function(d) { return d.x })
.attr("cy", function(d) { return d.y });
svgLinks
.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 });
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment