Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chenhunghan/6823041 to your computer and use it in GitHub Desktop.
Save chenhunghan/6823041 to your computer and use it in GitHub Desktop.
d3.js fundamentals of force(), nodes() and links()
doctype 5
html ->
head ->
meta charset: 'utf-8'
title 'hello'
script src: 'http://codeorigin.jquery.com/jquery-1.10.2.min.js'
script src: 'http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js'
script src: 'http://d3js.org/d3.v3.min.js'
link rel: 'stylesheet', href: 'http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css'
style '''
.link{
stroke: #000;
stroke-width: 3px;
}
.link2{
stroke: red;
stroke-width: 1px;
}
.node{
fill: #000;
stroke: #fff;
stroke-width: 1.5px;
}
.node2{
fill: red;
stroke: red;
stroke-width: 1px;
}
.node.a { fill: #1f77b4; }
.node.b { fill: #ff7f0e; }
.node.c { fill: #2ca02c; }
'''
body ->
input '#length', type: "range", min: "0", max: "300"
coffeescript ->
width = 950
height = 500
d = 300
a = {id: "a"}
b = {id: "b"}
c = {id: "c"}
nodes = []
links = []
nodes.push(a, b, c)
for i in [0..2]
nodes[i].x = width/2
nodes[i].y = height/2
nodes[1].fixed = true
console.log nodes
links.push({source: a, target: b}, {source: a, target: c}, {source: b, target: c})
force = d3.layout.force().nodes(nodes).links(links).size([width, height])
.linkDistance(d).on "tick", () ->
link.attr("x1", (d) -> d.source.x)
.attr("y1", (d) -> d.source.y)
.attr("x2", (d) -> d.target.x)
.attr("y2", (d) -> d.target.y)
node.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
.start()
svg = d3.select("body").append("svg").attr("width", width).attr("height", height)
contrl = d3.select("#length").on("change", () ->
p = $("#length").val()
force.linkDistance(p).start())
link = svg.selectAll('.link').data(force.links(), (d) -> d.source.id + "-" + d.target.id).enter().insert('line', '.node').attr("class", (d) -> "link" + " " + d.source.id + d.target.id)
node = svg.selectAll('.node').data(force.nodes(), (d) -> d.id).enter().append('circle').attr('class', (d) -> "node " + d.id).attr("r", 8).call(force.drag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment