旋转矩形.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * rect: [left, top, w, h]
  3. * radar: [radarX, radarY]
  4. * angle: 0, 90, 180, 270
  5. * 返回旋转后的矩形 [left, top, w, h]
  6. */
  7. function rotateRect(rect, radar, angle) {
  8. const [left, top, w, h] = rect;
  9. const [cx, cy] = radar;
  10. // 矩形四个角
  11. const corners = [
  12. [left, top],
  13. [left + w, top],
  14. [left + w, top + h],
  15. [left, top + h]
  16. ];
  17. const newCorners = corners.map(([x, y]) => {
  18. const dx = x - cx;
  19. const dy = y - cy;
  20. let nx, ny;
  21. switch (angle) {
  22. case 0:
  23. nx = dx;
  24. ny = dy;
  25. break;
  26. case 90:
  27. nx = dy;
  28. ny = -dx;
  29. break;
  30. case 180:
  31. nx = -dx;
  32. ny = -dy;
  33. break;
  34. case 270:
  35. nx = -dy;
  36. ny = dx;
  37. break;
  38. default:
  39. throw new Error("angle must be 0, 90, 180, 270");
  40. }
  41. return [cx + nx, cy + ny];
  42. });
  43. const xs = newCorners.map(p => p[0]);
  44. const ys = newCorners.map(p => p[1]);
  45. const newLeft = Math.min(...xs);
  46. const newTop = Math.min(...ys);
  47. const newW = Math.max(...xs) - newLeft;
  48. const newH = Math.max(...ys) - newTop;
  49. return [newLeft, newTop, newW, newH];
  50. }
  51. // 测试
  52. const rect = [0, 0, 2, 1];
  53. const radar = [2, 1];
  54. [0, 90, 180, 270].forEach(angle => {
  55. const newRect = rotateRect(rect, radar, angle);
  56. console.log(`angle=${angle}:`, newRect);
  57. });
  58. // 预期输出
  59. // angle=0: [0, 0, 2, 1]
  60. // angle=90: [2, -1, 1, 2]
  61. // angle=180: [2, 1, 2, 1]
  62. // angle=270: [1, 1, 1, 2]