我有一个可以绘制的 svg 路径。使用d3js
,我使用d3.geom.hull(...)
计算路径周围的凸包。现在我有一些 svg 对象,例如节点 (svg:circle),我想知道该节点是否在船体中。我怎样才能意识到这一点?这是我的 svg View 中的图片:
编辑: 我的目标是外壳中的节点元素(位于路径内),而不仅仅是路径的边缘。
最佳答案
这是一个简单的方法:
计算你的船体几何形状,返回 d3.geom.hull 给你的坐标数组。
将新点添加到原始数据数组中,并在此数组上再次计算 d3.geom.hull。
将步骤 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/