block by harrystevens 12cb2b63601c0baecc7d29a027b1f8ae

Convex Hull

Full Screen

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

index.html

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