Skip to content

Instantly share code, notes, and snippets.

@hughes
Last active Aug 29, 2015
Embed
What would you like to do?
grid-constrained force layout
{"description":"grid-constrained force layout","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"pingpong","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01,"ajax-caching":true,"thumbnail":"http://i.imgur.com/nirCJtB.png"}
var nodes = [];
var nodeCount = 200;
var width = 1000, height=450;
var gridSize = 150;
var gridForce = 3;
var i = nodeCount; while (i--) { nodes.push({x: Math.random()*width, y: Math.random() * height}); }
var svg = d3.select('svg');
var force = d3.layout.force()
.nodes(nodes)
.gravity(0)
.charge(-30)
.size([width, height])
.on('tick', tick);
var node = svg.selectAll('circle').data(nodes);
node.enter()
.append('circle')
.attr('r', 8)
.style('fill', '#f00')
.style('stroke', '#000')
.call(force.drag);
node.attr('cx', function (d) { return d.x; })
.attr('cy', function (d) { return d.y; });
function tick(e) {
var k = 0.1 * e.alpha;
nodes.forEach(function (d, i) {
// compute distance from grid
var fx = d.x % gridSize - gridSize / 2;
var fy = d.y % gridSize - gridSize / 2;
d.x -= fx * k * gridForce;
d.y -= fy * k * gridForce;
});
node.attr('cx', function (d) { return d.x; })
.attr('cy', function (d) { return d.y; });
}
force.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment