diff options
| author | kj_sh604 | 2026-03-15 16:19:35 -0400 |
|---|---|---|
| committer | kj_sh604 | 2026-03-15 16:19:35 -0400 |
| commit | 6ec259a0e71174651bae95d4628138bf6fd68742 (patch) | |
| tree | 5e33c6a5ec091ecabfcb257fdc7b6a88ed8754ac /packages/excalidraw/points.ts | |
| parent | 16c8578b15c727f22921f8a80a56ee4d4e7f2272 (diff) | |
refactor: packages/
Diffstat (limited to 'packages/excalidraw/points.ts')
| -rw-r--r-- | packages/excalidraw/points.ts | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/packages/excalidraw/points.ts b/packages/excalidraw/points.ts new file mode 100644 index 0000000..9d48857 --- /dev/null +++ b/packages/excalidraw/points.ts @@ -0,0 +1,63 @@ +import { + pointFromPair, + type GlobalPoint, + type LocalPoint, +} from "@excalidraw/math"; + +export const getSizeFromPoints = ( + points: readonly (GlobalPoint | LocalPoint)[], +) => { + const xs = points.map((point) => point[0]); + const ys = points.map((point) => point[1]); + return { + width: Math.max(...xs) - Math.min(...xs), + height: Math.max(...ys) - Math.min(...ys), + }; +}; + +/** @arg dimension, 0 for rescaling only x, 1 for y */ +export const rescalePoints = <Point extends GlobalPoint | LocalPoint>( + dimension: 0 | 1, + newSize: number, + points: readonly Point[], + normalize: boolean, +): Point[] => { + const coordinates = points.map((point) => point[dimension]); + const maxCoordinate = Math.max(...coordinates); + const minCoordinate = Math.min(...coordinates); + const size = maxCoordinate - minCoordinate; + const scale = size === 0 ? 1 : newSize / size; + + let nextMinCoordinate = Infinity; + + const scaledPoints = points.map((point): Point => { + const newCoordinate = point[dimension] * scale; + const newPoint = [...point]; + newPoint[dimension] = newCoordinate; + if (newCoordinate < nextMinCoordinate) { + nextMinCoordinate = newCoordinate; + } + return newPoint as Point; + }); + + if (!normalize) { + return scaledPoints; + } + + if (scaledPoints.length === 2) { + // we don't translate two-point lines + return scaledPoints; + } + + const translation = minCoordinate - nextMinCoordinate; + + const nextPoints = scaledPoints.map((scaledPoint) => + pointFromPair<Point>( + scaledPoint.map((value, currentDimension) => { + return currentDimension === dimension ? value + translation : value; + }) as [number, number], + ), + ); + + return nextPoints; +}; |
