D3.js: d3-delaunay - 如何开始?

D3.js: d3-delaunay - how to get started?

我们如何使用 D3.js、d3-delaunay 来创建 Voronoi 背景?来自 official page is really hard to follow. The example page is even worst. For example 的指南:

view = {
  const context = DOM.context2d(width, height);
  context.clearRect(0, 0, width, height);

  context.fillStyle = "black";
  context.beginPath();
  voronoi.delaunay.renderPoints(context, 1);
  context.fill();

  context.lineWidth = 1.5;

  const segments = voronoi.render().split(/M/).slice(1);

  let i = 0;
  for (const e of segments) {
    context.beginPath();
    context.strokeStyle = d3.hsl(360 * Math.random(), 0.7, 0.5);
    context.stroke(new Path2D("M" + e));
    if (i++ % 5 === 0) yield context.canvas;
  }
}

没有其他基本代码结构 - 导入 D3、声明变量和定位 HTML 元素。那么如何申请和使用这个view对象呢?

我在网上查了一下。仍然找不到 d3-delaunay 的任何可靠指南。有什么想法吗?

编辑:

我只想在网页上使用 d3-delaunay,普通的 HTML 和经典的 JS,没有来自 Observerable HQ 的任何东西。但是来自 D3.js 的文档与 Observable HQ 紧密结合。所以我完全不知道如何让 d3-delaunay 工作。

D3.js 的创建者或团队似乎从不关心 Observerable HQ 对某些用户有多不友好和违反直觉。像 Codepen 这样的平台很棒。但是,如何构思和创建像 Observable HQ 这样的平台呢?它在 JavaScript 库上创建了另一个 BIG 不必要的障碍层。

这是一个可能的转换代码。请注意,您可以轻松地将 DOM API 与 Observablehq 抽象连接起来,从而失去 Observablehq 运行时的反应性。

<script type="module">

    import * as d3 from "https://cdn.skypack.dev/d3@7";

    const w = window.innerWidth;
    const h = (w * 9) / 16;
    const canvas = document.createElement("canvas"); 
    const context = canvas.getContext("2d"); // DOM.context2d(width, height);

    canvas.width = w;
    canvas.height = h;

    const data = Array(100)
      .fill()
      .map((_, i) => ({ x: (i * w) / 100, y: Math.random() * h }));

    const voronoi = d3.Delaunay.from(
      data,
      (d) => d.x,
      (d) => d.y
    ).voronoi([0, 0, w, h]);

    context.clearRect(0, 0, w, h);

    context.fillStyle = "black";
    context.beginPath();
    voronoi.delaunay.renderPoints(context, 1);
    context.fill();

    context.lineWidth = 1.5;

    const segments = voronoi.render().split(/M/).slice(1);
    let i = 0;
    for (const e of segments) {
      context.beginPath();
      context.strokeStyle = d3.hsl(360 * Math.random(), 0.7, 0.5);
      context.stroke(new Path2D("M" + e));
    }
// no yield context.canvas; as we're not on a generator

    document.querySelector("#app").appendChild(canvas);


</script>
<div id="app"></div>