block by aaizemberg 8063f8c2d1adb7c7ee68

voronoi (d3, v5, svg, simple example)

Full Screen

index.html

<!DOCTYPE html>
<head>
  <title>Voronoi 101</title>
  <meta charset="utf-8">
</head>
<body>

<script src="https://d3js.org/d3.v5.min.js"></script>

<script>
  var width = 960, height = 500;

  var c10 = d3.schemePaired;

  var vertices = d3.range(10).map(function(d) {
    return [Math.random() * width, Math.random() * height];
  });

  var voronoi = d3.voronoi().extent([[0, 0], [width, height]]);

  var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);

  var path = svg.append("g").selectAll("path");

  path.data( voronoi.polygons(vertices)  ).enter().append("path")
      .attr("stroke","white") 
      .attr("fill", function(d,i) {return c10[i % 10]} )
//    .attr("d", function(d) { return "M" + d.join("L") + "Z" } );
    .attr("d", polygon);

  function polygon(d) { 
    return "M" + d.join("L") + "Z"; 
  }
    
  svg.selectAll("circle").data(vertices).enter().append("circle").attr("r", 3)
   //.attr("transform", function(d) { return "translate(" + d + ")"; })
     .attr("cx", function(d) { return d[0]; } )
     .attr("cy", function(d) { return d[1]; } );
</script>

</body>
</html>