Geometry.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * Computes the distance between two points
  3. *
  4. * @param {Point} p
  5. * @param {Point} q
  6. *
  7. * @return {Number} distance
  8. */
  9. export function pointDistance(a, b) {
  10. if (!a || !b) {
  11. return -1;
  12. }
  13. return Math.sqrt(
  14. Math.pow(a.x - b.x, 2) +
  15. Math.pow(a.y - b.y, 2)
  16. );
  17. }
  18. /**
  19. * Returns true if the point r is on the line between p and q
  20. *
  21. * @param {Point} p
  22. * @param {Point} q
  23. * @param {Point} r
  24. * @param {Number} [accuracy=5] accuracy for points on line check (lower is better)
  25. *
  26. * @return {Boolean}
  27. */
  28. export function pointsOnLine(p, q, r, accuracy) {
  29. if (typeof accuracy === 'undefined') {
  30. accuracy = 5;
  31. }
  32. if (!p || !q || !r) {
  33. return false;
  34. }
  35. var val = (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x),
  36. dist = pointDistance(p, q);
  37. // @see http://stackoverflow.com/a/907491/412190
  38. return Math.abs(val / dist) <= accuracy;
  39. }
  40. var ALIGNED_THRESHOLD = 2;
  41. /**
  42. * Returns whether two points are in a horizontal or vertical line.
  43. *
  44. * @param {Point} a
  45. * @param {Point} b
  46. *
  47. * @return {String|Boolean} returns false if the points are not
  48. * aligned or 'h|v' if they are aligned
  49. * horizontally / vertically.
  50. */
  51. export function pointsAligned(a, b) {
  52. if (Math.abs(a.x - b.x) <= ALIGNED_THRESHOLD) {
  53. return 'h';
  54. }
  55. if (Math.abs(a.y - b.y) <= ALIGNED_THRESHOLD) {
  56. return 'v';
  57. }
  58. return false;
  59. }
  60. /**
  61. * Returns true if the point p is inside the rectangle rect
  62. *
  63. * @param {Point} p
  64. * @param {Rect} rect
  65. * @param {Number} tolerance
  66. *
  67. * @return {Boolean}
  68. */
  69. export function pointInRect(p, rect, tolerance) {
  70. tolerance = tolerance || 0;
  71. return p.x > rect.x - tolerance &&
  72. p.y > rect.y - tolerance &&
  73. p.x < rect.x + rect.width + tolerance &&
  74. p.y < rect.y + rect.height + tolerance;
  75. }
  76. /**
  77. * Returns a point in the middle of points p and q
  78. *
  79. * @param {Point} p
  80. * @param {Point} q
  81. *
  82. * @return {Point} middle point
  83. */
  84. export function getMidPoint(p, q) {
  85. return {
  86. x: Math.round(p.x + ((q.x - p.x) / 2.0)),
  87. y: Math.round(p.y + ((q.y - p.y) / 2.0))
  88. };
  89. }