Skip to content

Instantly share code, notes, and snippets.

@jussi-kalliokoski
Created December 1, 2016 13:54
Show Gist options
  • Save jussi-kalliokoski/4d991933bb6a944603362da7166cf135 to your computer and use it in GitHub Desktop.
Save jussi-kalliokoski/4d991933bb6a944603362da7166cf135 to your computer and use it in GitHub Desktop.
Ideal sprite sheet size resolver
export const getSheetSize = (spriteWidth, spriteHeight, spriteCount) => {
const a = Math.max(spriteWidth, spriteHeight);
const b = Math.min(spriteWidth, spriteHeight);
let sizeA = 1 << (32 - Math.clz32(a));
let sizeB = 1 << (32 - Math.clz32(b));
let countA = 1;
let countB = 1;
while (spriteCount > countA * countB) {
if (sizeA < sizeB) {
sizeA <<= 1;
countA = Math.floor(sizeA / a);
} else {
sizeB <<= 1;
countB = Math.floor(sizeB / b);
}
}
const bounds = [countA * a, Math.ceil(spriteCount / countA) * b];
if (spriteWidth < spriteHeight) { bounds.reverse(); }
const [width, height] = bounds;
return { width, height };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment