util.ts 1.6 KB

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