forked from mbostock's block: Delaunay Force Mesh
Last active
January 4, 2018 00:47
-
-
Save juanprq/557ea220dda537933966b7d355eac980 to your computer and use it in GitHub Desktop.
Delaunay Force Mesh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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