Skip to content

Instantly share code, notes, and snippets.

@juanprq
Last active January 4, 2018 00:47
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 juanprq/557ea220dda537933966b7d355eac980 to your computer and use it in GitHub Desktop.
Save juanprq/557ea220dda537933966b7d355eac980 to your computer and use it in GitHub Desktop.
Delaunay Force Mesh
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>
canvas {
background-color: beige;
}
</style>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
const width = 960;
const height = 500;
const tau = 2 * Math.PI;
const random = (mult) => () => Math.random() * mult;
const randomW = random(width);
const randomH = random(height);
const numberOfNodes = 200;
const nodes = d3
.range(numberOfNodes)
.map(() => ({
x: randomW(),
y: randomH(),
}));
const voronoi = d3
.geom
.voronoi()
.x(d => d.x)
.y(d => d.y);
const leftNodes = nodes.slice(0, numberOfNodes / 2);
const rightNodes = nodes.slice(numberOfNodes / 2);
const leftLinks = voronoi.links(leftNodes);
const rightLinks = voronoi.links(rightNodes);
const canvas = d3
.select('body')
.append('canvas')
.attr('width', width)
.attr('height', height);
const context = canvas.node().getContext('2d');
const makeTicked = (nodes, links) => () => {
context.clearRect(0, 0, width, height);
context.beginPath();
links.forEach(function(d) {
context.moveTo(d.source.x, d.source.y);
context.lineTo(d.target.x, d.target.y);
});
context.lineWidth = 1;
context.strokeStyle = "#bbb";
context.stroke();
context.beginPath();
nodes.forEach(function(d) {
context.moveTo(d.x, d.y);
context.arc(d.x, d.y, 2, 0, tau);
});
context.lineWidth = 3;
context.strokeStyle = "#fff";
context.stroke();
context.fillStyle = "#000";
context.fill();
};
const leftForce = d3.layout.force()
.size([0, height])
.linkDistance(20)
.charge(-70)
.nodes(leftNodes)
.links(leftLinks)
.on('tick', makeTicked(leftNodes, leftLinks))
.start();
const rightForce = d3.layout.force()
.size([width, height])
.linkDistance(20)
.charge(-70)
.nodes(rightNodes)
.links(rightLinks)
.on('tick', makeTicked(rightNodes, rightLinks))
.start();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment