math - 从矩形点查找方向

标签 math canvas geometry coordinates draw

我试图从四个坐标中找出角的方向。也许一个例子比我的话更能描述..

    var points = [
     [0, 0], // top-left
     [50, 0], // top-right
     [50, 50], // bottom-right
     [0, 50], // bottom-left
   ]; // order can be random

    var topLeft =[9999, 9999]; 
    var topRight =[0, 9999]; 
    var bottomRight =[0, 0]; 
    var bottomLeft =[9999, 0]; 

    points.forEach((p) {
      if (p[0] < topLeft[0] && p[1] < topLeft[1]) topLeft = p;
      if (p[0] > topRight[0] && p[1] < topRight[1]) topRight = p;
      if (p[0] > bottomRight[0] && p[1] > bottomRight[1]) bottomRight = p;
      if (p[0] < bottomLeft[0] && p[1] > bottomLeft[1]) bottomLeft = p;
    });

    print([tl, tr, br, bl]);

  // [[0, 0], [50, 0], [50, 50], [50, 50]] - wrong
  // [[0, 0], [50, 0], [50, 50], [0, 50]] - right 

我有一个包含 4 个坐标点的列表。尝试根据方向将它们分开,例如左上、右上、左下、右下等。 但我的代码无法正常工作(右上角和左下角错误),您能帮我解决这个问题吗?以及如何提高效率?

最佳答案

您错过了 if 条件中的=(等号)。 这是更新后的代码。

void main() {
  var points = [
     [0, 0], // top-left
     [50, 0], // top-right
     [50, 50], // bottom-right
     [0, 50], // bottom-left
   ]; // order can be random

    var topLeft =[9999, 9999]; 
    var topRight =[0, 9999]; 
    var bottomRight =[0, 0]; 
    var bottomLeft =[9999, 0]; 

    points.forEach((p) {
      if (p[0] <= topLeft[0] && p[1] <= topLeft[1]) topLeft = p;
      if (p[0] >= topRight[0] && p[1] <= topRight[1]) topRight = p;
      if (p[0] >= bottomRight[0] && p[1] >= bottomRight[1]) bottomRight = p;
      if (p[0] <= bottomLeft[0] && p[1] >= bottomLeft[1]) bottomLeft = p;
    });

    print([topLeft, topRight, bottomRight, bottomLeft]);
}

关于math - 从矩形点查找方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63220234/

相关文章:

java - 用于 java 或 scala 中整数分解的库

algorithm - 给定 N 个点,如何找到圆上的最大点数?

javascript - 您会将哪种技术用于物理模拟 SVG 或 Canvas?

javascript - 将一个小位图多次绘制到 <canvas> 上?

Python OpenCV HoughCircles 没有给出好的结果

c++ - 有效地获取给定数字的所有除数

swift - 从整数值形成一个整数数组

javascript - 如何停止使用 canvas imageData 进行 alpha 预乘?

c - 给定两点和半径求圆心

python - Python中的三角波形数组