Skip to content

Instantly share code, notes, and snippets.

@basilesimon
Last active March 3, 2019 18:30
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 basilesimon/bac0542c8240d58c248b0e65ca716bf6 to your computer and use it in GitHub Desktop.
Save basilesimon/bac0542c8240d58c248b0e65ca716bf6 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.

forked from mbostock's block: Isolating Forces

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