Javascript 画布通过定位点将矩形与矩形连接起来

Javascript 画布通过定位点将矩形与矩形连接起来,javascript,canvas,Javascript,Canvas,我画了一张画布。我画了一些矩形物体 class Rectangle extends Shape{ constructor(posTopLeft, width, height){ const halfWidth = width * 0.5; const halfHeight = height * 0.5; super(width, height, new Position(posTopLeft.x + halfWidth, posTopLeft.y + halfH

我画了一张画布。我画了一些矩形物体

class Rectangle extends Shape{
    constructor(posTopLeft, width, height){
    const halfWidth = width * 0.5;
    const halfHeight = height * 0.5;

    super(width, height, new Position(posTopLeft.x + halfWidth, posTopLeft.y + halfHeight)); // set width, height and center position

    this.centerLeftPosition = new Position(this.centerPosition.x - halfWidth, this.centerPosition.y);
    this.centerRightPosition = new Position(this.centerLeftPosition.x + width, this.centerLeftPosition.y);
    this.centerTopPosition = new Position(this.centerPosition.x, this.centerPosition.y - halfHeight);
    this.centerBottomPosition = new Position(this.centerPosition.x, this.centerTopPosition.y + height);

    this.topLeftPosition = posTopLeft;
    this.bottomLeftPosition = new Position(this.topLeftPosition.x, this.topLeftPosition.y + height);
    this.topRightPosition = new Position(this.topLeftPosition.x + width, this.topLeftPosition.y);
    this.bottomRightPosition = new Position(this.topRightPosition.x, this.bottomLeftPosition.y);
  }
}

我还想画一条从一个矩形到另一个矩形的线

class Lane{
    constructor(startRect, targetRect){
       this.startRect = startRect;
       this.targetRect = targetRect;
  }
}
如果车道试图计算最短路径,如何通过车道连接这两个矩形

意味着如果一条直线正好位于另一条直线的上方,车道将从第一条直线的中心底部到第二条直线的中心顶部


如果第一个矩形在左边,第二个在右边,车道将从另一个矩形的右中到左中。

只需计算从一个矩形的每个点到另一个矩形的每个点的距离,然后对列表进行排序并选择最短的一个

例如,您将有两个列表,一个用于一个矩形中的所有点-现在您迭代第一个列表,并为每个点计算到其他矩形中所有点的距离

rectangle1[].foreach(function(point) {
distances.push(getDistance(point, point));
});
然后您只需
距离。sort()
即可获得最短的距离

要知道是哪一个,您可以将对象保存在包含其他点的坐标或名称的距离中,或者制作一个字典,在其中保存什么距离对应于什么名称-对于后一个,您只需分别处理多个点的距离相等的情况,而对于第一个问题,您不能只对像
{42,{pointA:[32,12],pointB:[42,64]}}
这样的东西进行排序,因此您必须编写一个函数来收集距离,然后再进行排序


两者最终都是一样的,希望我能帮上忙,干杯

检查所有可能的连接并找到最短的连接