美文网首页
前端判断矩形和线段是否相交的方法

前端判断矩形和线段是否相交的方法

作者: 花影_62b4 | 来源:发表于2022-06-10 10:34 被阅读0次
    export function isLineIntersectRectangle(
      polyline: Array<any>,
      rectangleLeftTopX: number,
      rectangleLeftTopY: number,
      rectangleRightBottomX: number,
      rectangleRightBottomY: number
    ): boolean {
      let linePointX1: number = polyline[0].x,
        linePointY1: number = polyline[0].y,
        linePointX2: number = polyline[1].x,
        linePointY2: number = polyline[1].y;
      let lineHeight = linePointY1 - linePointY2;
      let lineWidth = linePointX2 - linePointX1; // 计算叉乘
      let c = linePointX1 * linePointY2 - linePointX2 * linePointY1;
      if (
        (lineHeight * rectangleLeftTopX + lineWidth * rectangleLeftTopY + c >= 0 &&
          lineHeight * rectangleRightBottomX +
            lineWidth * rectangleRightBottomY +
            c <=
            0) ||
        (lineHeight * rectangleLeftTopX + lineWidth * rectangleLeftTopY + c <= 0 &&
          lineHeight * rectangleRightBottomX +
            lineWidth * rectangleRightBottomY +
            c >=
            0) ||
        (lineHeight * rectangleLeftTopX + lineWidth * rectangleRightBottomY + c >=
          0 &&
          lineHeight * rectangleRightBottomX + lineWidth * rectangleLeftTopY + c <=
            0) ||
        (lineHeight * rectangleLeftTopX + lineWidth * rectangleRightBottomY + c <=
          0 &&
          lineHeight * rectangleRightBottomX + lineWidth * rectangleLeftTopY + c >=
            0)
      ) {
        if (rectangleLeftTopX > rectangleRightBottomX) {
          let temp = rectangleLeftTopX;
          rectangleLeftTopX = rectangleRightBottomX;
          rectangleRightBottomX = temp;
        }
        if (rectangleLeftTopY < rectangleRightBottomY) {
          let temp1 = rectangleLeftTopY;
          rectangleLeftTopY = rectangleRightBottomY;
          rectangleRightBottomY = temp1;
        }
        if (
          (linePointX1 < rectangleLeftTopX && linePointX2 < rectangleLeftTopX) ||
          (linePointX1 > rectangleRightBottomX &&
            linePointX2 > rectangleRightBottomX) ||
          (linePointY1 > rectangleLeftTopY && linePointY2 > rectangleLeftTopY) ||
          (linePointY1 < rectangleRightBottomY &&
            linePointY2 < rectangleRightBottomY)
        ) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    }
    

    相关文章

      网友评论

          本文标题:前端判断矩形和线段是否相交的方法

          本文链接:https://www.haomeiwen.com/subject/hgavmrtx.html