Serves as a basis for other force layout examples.
forked from erkal's block: Basic Force Layout
license: gpl-3.0 |
Serves as a basis for other force layout examples.
forked from erkal's block: Basic Force Layout
<!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="//d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<script> | |
var width = 457, | |
height = 500, | |
nodes = [{},{},{},{},{}], | |
links = [{source: 0, target: 1}, {source: 1, target: 2}, {source: 2, target: 3}, {source: 3, target: 4}, {source: 4, target: 0}]; | |
var force = d3.layout.force() | |
.size([width, height]) | |
.nodes(nodes) | |
.links(links) | |
.linkDistance(38) | |
.charge(-475) | |
.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", 9) | |
.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> |