Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active January 12, 2017 15:33
Show Gist options
  • Save mbostock/b1f0ee970299756bc12d60aedf53c13b to your computer and use it in GitHub Desktop.
Save mbostock/b1f0ee970299756bc12d60aedf53c13b to your computer and use it in GitHub Desktop.
Isolating Forces
license: gpl-3.0

This example demonstrates how to patch force.initialize such that a force applies only to a subset of nodes in a simulation.

function isolate(force, filter) {
  var initialize = force.initialize;
  force.initialize = function() { initialize.call(force, nodes.filter(filter)); };
  return force;
}

Another way of having forces only apply to some nodes is to set the force strength to zero for those nodes by using a custom strength accessor (e.g., x.x). But if you have lots of isolated forces and lots of nodes, it is faster to isolate the force to a subset of nodes than to set the strength to zero for unaffected nodes.

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="500"></canvas>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var n = 20;
var nodes = d3.range(n * n).map(function(i) {
return {
index: i,
color: i < 200 ? "brown" : "steelblue"
};
});
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
var simulation = d3.forceSimulation(nodes)
.force("y", d3.forceY())
.force("brown", isolate(d3.forceX(-width / 6), function(d) { return d.color === "brown"; }))
.force("steelblue", isolate(d3.forceX(width / 6), function(d) { return d.color === "steelblue"; }))
.force("charge", d3.forceManyBody().strength(-10))
.on("tick", ticked);
function ticked() {
context.clearRect(0, 0, width, height);
context.save();
context.translate(width / 2, height / 2);
nodes.forEach(drawNode);
context.restore();
}
function drawNode(d) {
context.beginPath();
context.moveTo(d.x + 3, d.y);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
context.fillStyle = d.color;
context.fill();
}
function isolate(force, filter) {
var initialize = force.initialize;
force.initialize = function() { initialize.call(force, nodes.filter(filter)); };
return force;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment