javascript - 凸包(路径)中是否有 svg 元素?

标签 javascript svg d3.js

我有一个可以绘制的 svg 路径。使用d3js,我使用d3.geom.hull(...)计算路径周围的凸包。现在我有一些 svg 对象,例如节点 (svg:circle),我想知道该节点是否在船体中。我怎样才能意识到这一点?这是我的 svg View 中的图片:

View of the SVG

编辑: 我的目标是外壳中的节点元素(位于路径内),而不仅仅是路径的边缘。

最佳答案

这是一个简单的方法:

  1. 计算你的船体几何形状,返回 d3.geom.hull 给你的坐标数组。

  2. 将新点添加到原始数据数组中,并在此数组上再次计算 d3.geom.hull。

  3. 将步骤 1 返回的点数组与步骤 2 返回的点数组进行比较,以查看计算的外壳是否已更改。如果有,则该点位于凸包之外。如果没有变化,那么它就在凸包内部。

如果您有一个非常大的数据集,这可能会消耗性能。

这里有一些简单的代码来演示:

   // Some Random points
   var coords = d3.range(50).map(function() {return [Math.random(),Math.random()]})
   yourHull = d3.geom.hull(coords)
   // Random new point
   newCoord = [Math.random(),Math.random()]
   coords.push(newCoord)
   newHull = d3.geom.hull(coords)

   //The easy case to spot
   if (newHull.length != yourHull.length) {
      console.log("Outside")
   }
   //If the array lengths are the same, the point values may have changed
   else {
   var outside = false;
   for (var x = 0; x < yourHull.length;x++) {
      for (var y = 0; y < 2;y++) {
         if (yourHull[x][y] != newHull[x][y]) {
            outside = true;
            break;
         }
      }
   }

   if (outside) {
      console.log("outside")
   }
   else {
      console.log("on the hull")
   }
  }

关于javascript - 凸包(路径)中是否有 svg 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177348/

相关文章:

javascript - 使用 google api 地址更新 jQuery jqgrid 列

javascript - 如何获得 svg 中的标记结束位置?

javascript - 使用 d3.js 创建径向图表

javascript - 新数据的D3JS刷新图

javascript - document.location.hash 在 Safari 中不起作用

javascript - 换行符 - React Prop

javascript - 根据部分匹配查找 div id 的值

xml - 如何降低 svg 滤镜中 alpha 层的不透明度?

Javascript 干扰第二个 SVG 线动画

javascript - 从 JSON 调用和重绘更新包布局的数据