Skip to content

Instantly share code, notes, and snippets.

@Andrew-Reid
Last active November 29, 2017 03:45
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 Andrew-Reid/6e32f4cc9210ce3b9fb0a728238ae367 to your computer and use it in GitHub Desktop.
Save Andrew-Reid/6e32f4cc9210ce3b9fb0a728238ae367 to your computer and use it in GitHub Desktop.
Convex Hull with Centered Text

A quick v4 update to this v3 block.

There are a few changes to facilitate the use of a title centered on the convex hull centroid:

// create a polygon
var polygon = d3.polygonHull(vertices.map(function(d) { return d; }) );	

// use the polygon to update the convex hull
hull.datum(polygon).attr("d", function(d) { return "M" + d.join("L") + "Z"; });

// also use it to place the text (raise so it stays above new nodes)
text.attr("transform","translate("+d3.polygonCentroid(polygon)+")").raise(); 
<!DOCTYPE html>
<meta charset="utf-8">
<title>Convex Hull</title>
<style>
rect {
fill: none;
pointer-events: all;
}
.hull {
fill: lightsteelblue;
stroke: lightsteelblue;
stroke-width: 32px;
stroke-linejoin: round;
}
circle {
fill: white;
stroke: yellow;
stroke-width: 1.5px;
}
text {
font-size: 32px;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 500;
var randomX = d3.randomNormal(width / 2, 60),
randomY = d3.randomNormal(height / 2, 60),
vertices = d3.range(100).map(function() { return [randomX(), randomY()]; });
var svg = d3.select("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(); });
svg.append("rect")
.attr("width", width)
.attr("height", height);
var hull = svg.append("path")
.attr("class", "hull");
var circle = svg.selectAll("circle");
var text = svg.append("text").text("Hull Title").attr("text-anchor","middle");
redraw();
function redraw() {
var polygon = d3.polygonHull(vertices.map(function(d) { return d; }) );
hull.datum(polygon).attr("d", function(d) { return "M" + d.join("L") + "Z"; });
text.attr("transform","translate("+d3.polygonCentroid(polygon)+")").raise();
circle = svg.selectAll("circle").data(vertices);
circle.enter().append("circle").attr("r", 3).attr("transform", function(d) { return "translate(" + d + ")"; });
circle.attr("transform", function(d) { return "translate(" + d + ")"; });
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment