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
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> |