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

2022-06-10  本文已影响0人  花影_62b4
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;
  }
}
上一篇下一篇

猜你喜欢

热点阅读