Skip to content

Instantly share code, notes, and snippets.

@kristw
Created June 10, 2016 00:23
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 kristw/f9ffe87dd8b4038b5867e853c27cebb7 to your computer and use it in GitHub Desktop.
Save kristw/f9ffe87dd8b4038b5867e853c27cebb7 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.

forked from mbostock's block: Convex Hull

<!DOCTYPE html>
<meta charset="utf-8">
<title>Convex Hull</title>
<style>
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;
}
</style>
<body>
<button id="changeBtn">Change</button>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 500,
height = 500;
var randomX = d3.random.normal(width / 2, 60),
randomY = d3.random.normal(height / 2, 60);
function generatePoints(count){
return d3.range(count).map(function() {
return [randomX(), randomY()];
});
}
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
svg.append("rect")
.attr("width", width)
.attr("height", height);
var hull = svg.append("path")
.attr("class", "hull");
draw(generatePoints(10));
function draw(points) {
hull.datum(d3.geom.hull(points))
.transition()
.attr("d", function(d) {
return "M" + d.join("L") + "Z";
});
var selection = svg.selectAll("circle")
.data(points);
selection.enter()
.append("circle")
.attr("r", 3);
selection.transition()
.attr("transform", function(d) {
return "translate(" + d + ")";
});
selection.exit().remove();
}
document.getElementById('changeBtn').addEventListener('click', function(){
draw(generatePoints(Math.round(3 + Math.random()*6)));
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment