Skip to content

Instantly share code, notes, and snippets.

@Fil
Forked from mbostock/.block
Created July 28, 2020 10:43
Show Gist options
  • Select an option

  • Save Fil/b8025e91219af4538e28efb38d354639 to your computer and use it in GitHub Desktop.

Select an option

Save Fil/b8025e91219af4538e28efb38d354639 to your computer and use it in GitHub Desktop.
Force-Directed Lattice
license: gpl-3.0
height: 960

This demonstrates forceLink.iterations, which strengthens d3-force’s link constraint by applying the constraint multiple times per simulation step.

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="960"></canvas>
<script src="https://d3js.org/d3.v4.0.0-alpha.35.min.js"></script>
<script>
var n = 20;
var nodes = d3.range(n * n).map(function(i) {
return {
index: i
};
});
var links = [];
for (var y = 0; y < n; ++y) {
for (var x = 0; x < n; ++x) {
if (y > 0) links.push({source: (y - 1) * n + x, target: y * n + x});
if (x > 0) links.push({source: y * n + (x - 1), target: y * n + x});
}
}
var simulation = d3.forceSimulation(nodes)
.force("charge", d3.forceManyBody().strength(-30))
.force("link", d3.forceLink(links).distance(20).iterations(10))
.on("tick", ticked);
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
function ticked() {
context.clearRect(0, 0, width, height);
context.save();
context.translate(width / 2, height / 2);
context.beginPath();
links.forEach(drawLink);
context.strokeStyle = "#aaa";
context.stroke();
context.beginPath();
nodes.forEach(drawNode);
context.fill();
context.strokeStyle = "#fff";
context.stroke();
context.restore();
}
function drawLink(d) {
context.moveTo(d.source.x, d.source.y);
context.lineTo(d.target.x, d.target.y);
}
function drawNode(d) {
context.moveTo(d.x + 3, d.y);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment