Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active December 20, 2018 22:13
Show Gist options
  • Save HarryStevens/12cb2b63601c0baecc7d29a027b1f8ae to your computer and use it in GitHub Desktop.
Save HarryStevens/12cb2b63601c0baecc7d29a027b1f8ae to your computer and use it in GitHub Desktop.
Convex Hull

Compute the convex hull of a set of points with Geometric.js.

<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
polygon {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
text {
font-family: "Helvetica Neue", sans-serif;
font-size: 16px;
pointer-events: none;
text-anchor: middle;
}
</style>
</head>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://unpkg.com/geometric@1.0.0/build/geometric.min.js"></script>
<script>
var width = window.innerWidth, height = window.innerHeight, started = false;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var instructions = svg.append("text")
.attr("x", width / 2)
.attr("y", height / 2)
.text("Hover anywhere to start.");
var polygon = svg.append("polygon");
var points = [];
svg.on("mousemove", _ => {
if (!started){
instructions.transition().duration(750)
.attr("x", 10)
.attr("y", 20)
.style("text-anchor", "start")
.text("Click to reset.");
started = true;
}
var p = [d3.event.pageX, d3.event.pageY];
points.push(p);
svg.append("circle").attr("r", 2).attr("transform", "translate(" + p + ")");
polygon.attr("points", geometric.polygonHull(points));
});
svg.on("click", _ => {
instructions
.transition()
.style("opacity", 1e-6)
.remove();
d3.selectAll("circle").remove();
points = [];
polygon.attr("points", null);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment