Created
August 19, 2013 03:24
-
-
Save vicapow/6265529 to your computer and use it in GitHub Desktop.
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> | |
<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 = 800 | |
, h = 500 | |
, 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.9) | |
.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(){ | |
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() | |
setTimeout(function(){ | |
force.alpha(1) | |
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) | |
} | |
}) | |
}, 2000) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment