旋转点.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * point: [x, y]
  3. * radar: [radarX, radarY]
  4. * angle: 0, 90, 180, 270 顺时针旋转角度
  5. * 返回旋转后的点 [x2, y2]
  6. */
  7. function rotatePoint(point, radar, angle) {
  8. const [x, y] = point;
  9. const [cx, cy] = radar;
  10. const dx = x - cx;
  11. const dy = y - cy;
  12. let nx, ny;
  13. switch (angle) {
  14. case 0:
  15. nx = dx;
  16. ny = dy;
  17. break;
  18. case 90:
  19. nx = dy;
  20. ny = -dx;
  21. break;
  22. case 180:
  23. nx = -dx;
  24. ny = -dy;
  25. break;
  26. case 270:
  27. nx = -dy;
  28. ny = dx;
  29. break;
  30. default:
  31. throw new Error("angle must be 0, 90, 180, 270");
  32. }
  33. return [cx + nx, cy + ny];
  34. }
  35. // 测试
  36. const point = [3, 2];
  37. const radar = [2, 1];
  38. [0, 90, 180, 270].forEach(angle => {
  39. const newPoint = rotatePoint(point, radar, angle);
  40. console.log(`angle=${angle}:`, newPoint);
  41. });
  42. // 预期输出
  43. // angle=0: [3, 2]
  44. // angle=90: [2, 0]
  45. // angle=180: [1, 0]
  46. // angle=270: [2, 2]