points.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import {
  2. pointFromPair,
  3. type GlobalPoint,
  4. type LocalPoint,
  5. } from "@excalidraw/math";
  6. import type { NullableGridSize } from "@excalidraw/excalidraw/types";
  7. export const getSizeFromPoints = (
  8. points: readonly (GlobalPoint | LocalPoint)[],
  9. ) => {
  10. const xs = points.map((point) => point[0]);
  11. const ys = points.map((point) => point[1]);
  12. return {
  13. width: Math.max(...xs) - Math.min(...xs),
  14. height: Math.max(...ys) - Math.min(...ys),
  15. };
  16. };
  17. /** @arg dimension, 0 for rescaling only x, 1 for y */
  18. export const rescalePoints = <Point extends GlobalPoint | LocalPoint>(
  19. dimension: 0 | 1,
  20. newSize: number,
  21. points: readonly Point[],
  22. normalize: boolean,
  23. ): Point[] => {
  24. const coordinates = points.map((point) => point[dimension]);
  25. const maxCoordinate = Math.max(...coordinates);
  26. const minCoordinate = Math.min(...coordinates);
  27. const size = maxCoordinate - minCoordinate;
  28. const scale = size === 0 ? 1 : newSize / size;
  29. let nextMinCoordinate = Infinity;
  30. const scaledPoints = points.map((point): Point => {
  31. const newCoordinate = point[dimension] * scale;
  32. const newPoint = [...point];
  33. newPoint[dimension] = newCoordinate;
  34. if (newCoordinate < nextMinCoordinate) {
  35. nextMinCoordinate = newCoordinate;
  36. }
  37. return newPoint as Point;
  38. });
  39. if (!normalize) {
  40. return scaledPoints;
  41. }
  42. if (scaledPoints.length === 2) {
  43. // we don't translate two-point lines
  44. return scaledPoints;
  45. }
  46. const translation = minCoordinate - nextMinCoordinate;
  47. const nextPoints = scaledPoints.map((scaledPoint) =>
  48. pointFromPair<Point>(
  49. scaledPoint.map((value, currentDimension) => {
  50. return currentDimension === dimension ? value + translation : value;
  51. }) as [number, number],
  52. ),
  53. );
  54. return nextPoints;
  55. };
  56. // TODO: Rounding this point causes some shake when free drawing
  57. export const getGridPoint = (
  58. x: number,
  59. y: number,
  60. gridSize: NullableGridSize,
  61. ): [number, number] => {
  62. if (gridSize) {
  63. return [
  64. Math.round(x / gridSize) * gridSize,
  65. Math.round(y / gridSize) * gridSize,
  66. ];
  67. }
  68. return [x, y];
  69. };