vector.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. export function sub([x1, y1], [x2, y2]) {
  2. return [x1 - x2, y1 - y2];
  3. }
  4. export function add([x1, y1], [x2, y2]) {
  5. return [x1 + x2, y1 + y2];
  6. }
  7. export function dist([x0, y0], [x1, y1]) {
  8. return Math.sqrt(Math.pow((x0 - x1), 2) + Math.pow((y0 - y1), 2));
  9. }
  10. /**
  11. * Calculate angle of vector [x, y].
  12. */
  13. export function angle([x, y]) {
  14. return Math.atan2(y, x);
  15. }
  16. /**
  17. * Calculate angle of [x, y], then + Math.PI / 2.
  18. * Because of the difference between `Geometric coordinate system` and `Visualization coordinate system`.
  19. * @returns
  20. */
  21. export function angleWithQuadrant([x, y]) {
  22. return angle([x, y]) + Math.PI / 2;
  23. }
  24. export function angleBetween(v0, v1) {
  25. const a0 = angle(v0);
  26. const a1 = angle(v1);
  27. if (a0 < a1)
  28. return a1 - a0;
  29. return Math.PI * 2 - (a0 - a1);
  30. }
  31. export function calcBBox(points) {
  32. let minX = Infinity;
  33. let maxX = -Infinity;
  34. let minY = Infinity;
  35. let maxY = -Infinity;
  36. for (const [x, y] of points) {
  37. minX = Math.min(x, minX);
  38. maxX = Math.max(x, maxX);
  39. minY = Math.min(y, minY);
  40. maxY = Math.max(y, maxY);
  41. }
  42. const width = maxX - minX;
  43. const height = maxY - minY;
  44. return [minX, minY, width, height];
  45. }
  46. /**
  47. * Get the center of two points.
  48. */
  49. export function mid([x1, y1], [x2, y2]) {
  50. return [(x1 + x2) / 2, (y1 + y2) / 2];
  51. }
  52. //# sourceMappingURL=vector.js.map