当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


d3.js Delaunay.find()用法及代码示例


D3.js 是一个强大的数据可视化 JavaScript 框架,其模块之一 Delaunay 支持 Delaunay 三角剖分。这德劳奈.find()方法返回最接近指定点 (x, y) 的输入点的索引。

用法:

 delaunay.find(x, y[, i])

参数:

  • x: 要查找索引点的点的 x 坐标。
  • y:要查找索引点的点的 y 坐标。
  • 我(可选):它是一个可选参数,指示搜索的起始三角形索引。如果提供,则搜索从指定的三角形索引开始。

返回值:

Delaunay 三角形的索引包含指定点 (x, y)。

例子:此示例显示 delaunay.find() 方法的使用。

HTML


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="
https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
    <h1 style="text-align: center; color:
     green;">GeeksforGeeks</h1>
    <h3 style="text-align: center;">
        D3.js | d3.Delaunay.find() Method</h3>
    <div id="app" style="text-align: center;
     margin-top: 20px; font-size: 18px;"></div>
    <script type="module">
        import * as d3 from "https://cdn.skypack.dev/d3@7";
        const canvasWidth = 400;
        const canvasHeight = 300;
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        // Generating a set of random points
        const data = Array(50)  // Reduced number of points
            .fill()
            .map((_, i) => ({
                x: (i * canvasWidth) / 50,
                y: Math.random() * canvasHeight
            }));
        // Creating a Delaunay triangulation from the data
        const voronoi = d3.Delaunay.from(
            data,
            (d) => d.x,
            (d) => d.y
        ).voronoi([0, 0, canvasWidth, canvasHeight]);
        // Clearing the canvas
        context.clearRect(0, 0, canvasWidth, canvasHeight);
        // Rendering the Delaunay points on the canvas
        context.fillStyle = "black";
        context.beginPath();
        voronoi.delaunay.renderPoints(context, 1);
        context.fill();
        // Styling the Voronoi diagram
        context.lineWidth = 1.5;
        const segments = voronoi.render().split(/M/).slice(1);
        for (const e of segments) {
            context.beginPath();
            context.strokeStyle = d3.hsl(360 *
                Math.random(), 0.7, 0.5);
            context.stroke(new Path2D("M" + e));
        }
        // Using the find() method to locate 
        // the Delaunay triangle for the point (2, 3)
        const findResult = voronoi.delaunay.find(2, 3);
        // Displaying the result on the HTML page
        document.querySelector("#app").innerHTML =
            `Index of Delaunay Triangle 
            containing (2, 3): ${findResult}`;
        document.querySelector("#app").appendChild(canvas);
    </script>
</body>
</html>

输出:

MicrosoftTeams-image-(3)-(1)



相关用法


注:本文由纯净天空筛选整理自taran910大神的英文原创作品 D3.js Delaunay.find() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。