gaoluyang
2026-06-24 712aa51536236d43e87273e4ce45ac5691dffad8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/** 坐标点 */
export interface Point {
  x: number;
  y: number;
}
 
/** 矩形 */
export interface Rect {
  left: number; // 左上角 X 轴坐标
  top: number; // 左上角 Y 轴坐标
  right: number; // 右下角 X 轴坐标
  bottom: number; // 右下角 Y 轴坐标
  width: number; // 矩形宽度
  height: number; // 矩形高度
}
 
/**
 * 判断两个矩形是否重叠
 *
 * @param a 矩形 A
 * @param b 矩形 B
 */
export function isOverlap(a: Rect, b: Rect): boolean {
  return (
    a.left < b.left + b.width &&
    a.left + a.width > b.left &&
    a.top < b.top + b.height &&
    a.height + a.top > b.top
  );
}
 
/**
 * 检查坐标点是否在矩形内
 * @param hotArea 矩形
 * @param point 坐标
 */
export function isContains(hotArea: Rect, point: Point): boolean {
  return (
    point.x >= hotArea.left &&
    point.x < hotArea.right &&
    point.y >= hotArea.top &&
    point.y < hotArea.bottom
  );
}
 
/**
 * 在两个坐标点中间,创建一个矩形
 *
 * 存在以下情况:
 * 1. 两个坐标点是同一个位置,只占一个位置的正方形,宽高都为 1
 * 2. X 轴坐标相同,只占一行的矩形,高度为 1
 * 3. Y 轴坐标相同,只占一列的矩形,宽度为 1
 * 4. 多行多列的矩形
 *
 * @param a 坐标点一
 * @param b 坐标点二
 */
export function createRect(a: Point, b: Point): Rect {
  // 计算矩形的范围
  let [left, left2] = [a.x, b.x].toSorted();
  left = left ?? 0;
  left2 = left2 ?? 0;
  let [top, top2] = [a.y, b.y].toSorted();
  top = top ?? 0;
  top2 = top2 ?? 0;
  const right = left2 + 1;
  const bottom = top2 + 1;
  const height = bottom - top;
  const width = right - left;
  return { left, right, top, bottom, height, width };
}