Last active
November 23, 2020 19:01
-
-
Save steveruizok/87fd7c6150ff265ae77c1a3f1eb4a9e6 to your computer and use it in GitHub Desktop.
A function to distribute boxes evenly along either the x or y axis.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function distributeEvenly< | |
T extends { x: number; y: number; height: number; width: number } | |
>(axis: "x" | "y", boxes: T[]) { | |
const mboxes = [...boxes] | |
const extent = axis === "x" ? "width" : "height" | |
mboxes.sort((a, b) => a[axis] - b[axis]) | |
// Overall boxes span | |
const last = mboxes[mboxes.length - 1] | |
const dist = last[axis] + last[extent] - mboxes[0][axis] | |
// Space used by boxes | |
let span = 0 | |
for (let box of mboxes) { | |
span += box[extent] | |
} | |
// New distance between boxes | |
let step = (dist - span) / (mboxes.length - 1) | |
let pos = mboxes[0][axis] | |
for (let box of mboxes) { | |
if (Math.abs(pos - box[axis]) >= 1e-6) { | |
box[axis] += pos - box[axis] | |
} | |
pos += box[extent] | |
pos += step | |
} | |
return mboxes | |
} | |
// Adapted from https://gitlab.com/inkscape/inkscape/-/blob/master/src/actions/actions-object-align.cpp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment