概要 实例 介绍 源码

Voronoi镶嵌

源文件:index.html

  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <style>
  4. .links {
  5. stroke: #000;
  6. stroke-opacity: 0.2;
  7. }
  8. .polygons {
  9. fill: none;
  10. stroke: #000;
  11. }
  12. .polygons :first-child {
  13. fill: #f00;
  14. }
  15. .sites {
  16. fill: #000;
  17. stroke: #fff;
  18. }
  19. .sites :first-child {
  20. fill: #fff;
  21. }
  22. </style>
  23. <svg width="960" height="500"></svg>
  24. <script src="https://d3js.org/d3.v4.min.js"></script>
  25. <script>
  26. var svg = d3.select("svg").on("touchmove mousemove", moved),
  27. width = +svg.attr("width"),
  28. height = +svg.attr("height");
  29. var sites = d3.range(100)
  30. .map(function(d) { return [Math.random() * width, Math.random() * height]; });
  31. var voronoi = d3.voronoi()
  32. .extent([[-1, -1], [width + 1, height + 1]]);
  33. var polygon = svg.append("g")
  34. .attr("class", "polygons")
  35. .selectAll("path")
  36. .data(voronoi.polygons(sites))
  37. .enter().append("path")
  38. .call(redrawPolygon);
  39. var link = svg.append("g")
  40. .attr("class", "links")
  41. .selectAll("line")
  42. .data(voronoi.links(sites))
  43. .enter().append("line")
  44. .call(redrawLink);
  45. var site = svg.append("g")
  46. .attr("class", "sites")
  47. .selectAll("circle")
  48. .data(sites)
  49. .enter().append("circle")
  50. .attr("r", 2.5)
  51. .call(redrawSite);
  52. function moved() {
  53. sites[0] = d3.mouse(this);
  54. redraw();
  55. }
  56. function redraw() {
  57. var diagram = voronoi(sites);
  58. polygon = polygon.data(diagram.polygons()).call(redrawPolygon);
  59. link = link.data(diagram.links()), link.exit().remove();
  60. link = link.enter().append("line").merge(link).call(redrawLink);
  61. site = site.data(sites).call(redrawSite);
  62. }
  63. function redrawPolygon(polygon) {
  64. polygon
  65. .attr("d", function(d) { return d ? "M" + d.join("L") + "Z" : null; });
  66. }
  67. function redrawLink(link) {
  68. link
  69. .attr("x1", function(d) { return d.source[0]; })
  70. .attr("y1", function(d) { return d.source[1]; })
  71. .attr("x2", function(d) { return d.target[0]; })
  72. .attr("y2", function(d) { return d.target[1]; });
  73. }
  74. function redrawSite(site) {
  75. site
  76. .attr("cx", function(d) { return d[0]; })
  77. .attr("cy", function(d) { return d[1]; });
  78. }
  79. </script>