Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active Feb 9, 2016
Embed
What would you like to do?
Delaunay Force Mesh
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
τ = 2 * Math.PI;
var nodes = d3.range(400).map(function() {
return {
x: Math.random() * width,
y: Math.random() * height
};
});
var voronoi = d3.geom.voronoi()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; });
var links = voronoi.links(nodes);
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links)
.on("tick", ticked)
.start();
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
function ticked() {
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, τ);
});
context.lineWidth = 3;
context.strokeStyle = "#fff";
context.stroke();
context.fillStyle = "#000";
context.fill();
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment