Skip to content

Instantly share code, notes, and snippets.

Last active March 22, 2018 12:14
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/4341699 to your computer and use it in GitHub Desktop.
Convex Hull
license: gpl-3.0

This example uses d3.geom.hull to compute the 2D convex hull of a set of points. An outer stroke is used to pad the hull. Click to add a new point.

<!DOCTYPE html>
<meta charset="utf-8">
<title>Convex Hull</title>
rect {
fill: none;
pointer-events: all;
.hull {
fill: steelblue;
stroke: steelblue;
stroke-width: 32px;
stroke-linejoin: round;
circle {
fill: white;
stroke: black;
stroke-width: 1.5px;
<script src="//"></script>
var width = 960,
height = 500;
var randomX = d3.random.normal(width / 2, 60),
randomY = d3.random.normal(height / 2, 60),
vertices = d3.range(100).map(function() { return [randomX(), randomY()]; });
var svg ="body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousemove", function() { vertices[0] = d3.mouse(this); redraw(); })
.on("click", function() { vertices.push(d3.mouse(this)); redraw(); });
.attr("width", width)
.attr("height", height);
var hull = svg.append("path")
.attr("class", "hull");
var circle = svg.selectAll("circle");
function redraw() {
hull.datum(d3.geom.hull(vertices)).attr("d", function(d) { return "M" + d.join("L") + "Z"; });
circle =;
circle.enter().append("circle").attr("r", 3);
circle.attr("transform", function(d) { return "translate(" + d + ")"; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment