Skip to content

Instantly share code, notes, and snippets.

@vicapow
Created August 9, 2013 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vicapow/6191826 to your computer and use it in GitHub Desktop.
Save vicapow/6191826 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
body, html {
margin: 0;
}
/* show or hide the foci for debugging */
.foci-1, .foci-2{
/* display: none; */
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var w = window.innerWidth
, h = window.innerHeight
, svg = d3.select('body').append('svg')
.attr({ width: w, height: h })
, Force = function(nodes, links){
return d3.layout.force()
.nodes(nodes)
.links(links)
.gravity(0)
.size([w, h])
.linkDistance(0)
.linkStrength(0.1)
.friction(0.7)
.charge(function(d, i){ return d.charge })
}
, Nodes = function(num, id, name){
return d3.range(num).map(function(d){
return {
id : id
, x : Math.random() * w
, y : Math.random() * h
, charge : -10
, name : name
}
})
}
, Foci = function(x, y, name){
return { x : x, y : y, charge : 0, fixed : true, name : name }
}
, Links = function(nodes, foci){
return nodes.map(function(node){
return { source : node, target : foci }
})
}
, fill = function(d){
if(d) return 'red'
else return 'blue'
}
, nodes1 = Nodes(100, 0, 'node-1')
, nodes2 = Nodes(50, 1, 'node-2')
, foci1 = Foci(w / 2, h / 2, 'foci-1')
, foci2 = Foci(w / 2 + 200, h / 2, 'foci-2')
, links1 = Links(nodes1, foci1)
, links2 = Links(nodes2, foci2)
, all = nodes1.concat(nodes2).concat([foci1, foci2])
, force = Force(all, links1.concat(links2))
force.on('tick', function(){
force.alpha(1)
svg.selectAll('circle')
.attr('cx', function(d){ return d.x })
.attr('cy', function(d){ return d.y })
})
svg.selectAll('circle')
.data(all)
.enter().append('circle')
.attr({
cx: function(d) { return d.x }
, cy: function(d){ return d.y }
, r: 4
, 'class': function(d){ return d.name }
}).style({
fill: function(d){ return fill(d.id) }
, stroke: 'while'
, 'stroke-width': 1
})
force.start()
// d3.select('.foci-1').drag()
d3.select('.foci-2')
.transition()
.ease('cubic-in-out')
.duration(2000)
.tween('dataTween', function(d){
var ix = d3.interpolate(d.x, w / 2)
var iy = d3.interpolate(d.y, h / 2)
return function(t){
d.x = d.px = ix(t)
d.y = d.py = iy(t)
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment