计算顶点数组之间的距离

时间:2014-05-19 15:41:27

标签: javascript

我正在使用一个有70个顶点的面的库,是否有一个快速的方法/循环,我可以用来计算所有顶点之间的距离,并说例如我想插入点32和点之间的距离27并将其插入div。我目前正在使用它来获取每个点的坐标。

 var position = ctrack.getCurrentPosition();
                             edx1 = position[27][0];//Eyeposition left
                             edy1 = position[27][1];

                             edx2 = position[32][0];//Eyeposition Right
                             edy2 = position[32][1];

然后使用毕达哥拉斯定理计算差异,这似乎很慢并且想知道是否有更好的方法?

var distBetweenEyes = Math.sqrt( (edx1-edx2)*(edx1-edx2) + (edy1-edy2)*(edy1-edy2) );

下面的顶点图

enter image description here

我想知道我是否可以动态执行此操作,说我有一个计算所有70点之间距离的循环然后我希望能够快速存储任意两点之间的距离,以便我可以将该信息推送到我的HTML。

1 个答案:

答案 0 :(得分:1)

尝试:

function distance(i, j, data) {
    return Math.pow(data[i][0] - data[j][0], 2) + Math.pow(data[i][1] - data[j][1], 2);
}

(如Meredith所指出的,你不需要得到平方根值进行比较)

然后通过以下方式获得所需的距离:

var distBetweenEyes = distance(27, 32, position);
相关问题