用于绘制线javascript的循环逻辑 [英] Loop logic for drawing line javascript

查看:54
本文介绍了用于绘制线javascript的循环逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

var element_1 = new Array([x1,y1],[x2,y2],[x3,y3],[x4,y4]);
var element_2 = new Array([x1,y1],[x2,y2],[x3,y3],[x4,y4]);

逻辑:
我想运行一个循环(嵌套),其中每个元素都是 element_1 (例如 [x1,y1] )与 element_2 和它们之间的最短距离应在循环内计算(我知道如何计算最短路径)。这里棘手的部分是我需要一个参考,哪一对最短,然后获得那些 [x1,y1] [x2,y2 ] 绘制一条线的组合。

Logic: I want to run a loop (nested) where each element of element_1 (for eg [x1,y1]) is compared to each element of element_2 and the shortest distance between them shall be calculated within the loop (I know how to calculate the shortest path). The tricky part here is that I need a reference that which pair made the shortest past and then obtain those [x1,y1] and [x2,y2] combinations to draw a line.

示例数据:

var element_1 = new Array([10,0],[20,10],[10,20],[0,10]);
var element_2 = new Array([10,30],[20,40],[10,50],[0,40]);

行应在[10,20]和[10,30]之间进行。此外,我会以某种方式将坐标存储在某处以将其传递给线条绘制功能

Line should be made between [10,20] and [10,30]. Also, I would somehow need to store the coordinates somewhere to pass it to the line drawing function

我该怎么做?任何线索都将受到高度赞赏。

How can I do this? Any leads would be highly appreciated.

推荐答案

我会这样做:

var element_1 = [[0,0],[1,2],[5,3],[6,8]];
var element_2 = [[0,1],[1,4],[5,9],[9,8]];

var closest = {a: false, b: false, distance: false};

for(var i=0; i<element_1.length; i++) {
  for(var j=0; j<element_2.length; j++) {
    var distance = calculate_distance(element_1[i], element_2[j]);
    console.log('Distance between element_1['+i+'] and element_2['+j+']: ' + distance);
    if(closest.distance === false || distance < closest.distance) {
      closest = {a: element_1[i], b: element_2[j], distance: distance};
    }
  }
}

console.log('The shortest path is between '+closest.a+' and '+closest.b+', which is '+closest.distance);

function calculate_distance(a, b) {
  var width  = Math.abs( a[0] - b[0] ),
      height = Math.abs( a[1] - b[1] ),
      hypothenuse = Math.sqrt( width*width + height*height );
  return hypothenuse;
}

As Roko C. Buljan 说,在你的情况下,你只需要替换 new Array() with [] 这就是原因

As Roko C. Buljan said, in your case you can just replace new Array() with []. Here's why.

这篇关于用于绘制线javascript的循环逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆