math.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // https://stackoverflow.com/a/6853926/232122
  2. export function distanceBetweenPointAndSegment(
  3. x: number,
  4. y: number,
  5. x1: number,
  6. y1: number,
  7. x2: number,
  8. y2: number
  9. ) {
  10. const A = x - x1;
  11. const B = y - y1;
  12. const C = x2 - x1;
  13. const D = y2 - y1;
  14. const dot = A * C + B * D;
  15. const lenSquare = C * C + D * D;
  16. let param = -1;
  17. if (lenSquare !== 0) {
  18. // in case of 0 length line
  19. param = dot / lenSquare;
  20. }
  21. let xx, yy;
  22. if (param < 0) {
  23. xx = x1;
  24. yy = y1;
  25. } else if (param > 1) {
  26. xx = x2;
  27. yy = y2;
  28. } else {
  29. xx = x1 + param * C;
  30. yy = y1 + param * D;
  31. }
  32. const dx = x - xx;
  33. const dy = y - yy;
  34. return Math.hypot(dx, dy);
  35. }
  36. export function rotate(
  37. x1: number,
  38. y1: number,
  39. x2: number,
  40. y2: number,
  41. angle: number
  42. ) {
  43. // 𝑎′𝑥=(𝑎𝑥−𝑐𝑥)cos𝜃−(𝑎𝑦−𝑐𝑦)sin𝜃+𝑐𝑥
  44. // 𝑎′𝑦=(𝑎𝑥−𝑐𝑥)sin𝜃+(𝑎𝑦−𝑐𝑦)cos𝜃+𝑐𝑦.
  45. // https://math.stackexchange.com/questions/2204520/how-do-i-rotate-a-line-segment-in-a-specific-point-on-the-line
  46. return [
  47. (x1 - x2) * Math.cos(angle) - (y1 - y2) * Math.sin(angle) + x2,
  48. (x1 - x2) * Math.sin(angle) + (y1 - y2) * Math.cos(angle) + y2
  49. ];
  50. }