Serves as a basis for other force layout examples.
Last active
August 29, 2015 13:57
-
-
Save erkal/9746488 to your computer and use it in GitHub Desktop.
Basic Force Layout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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