@altano/satori-fit-text
Version:
Fit text to a bounding box in Node or the browser
24 lines (22 loc) • 1.25 kB
JavaScript
import { getTextMeasurer } from "./TextMeasurer/getTextMeasurer.js";
//#region src/fitText.ts
/**
* Given text, dimensions, and some options, returns the largest font size that
* would keep the text contained within the dimensions.
*/
async function findLargestUsableFontSize({ text, font, maxWidth, maxHeight, lineHeight = "normal", minFontSize = 1, maxFontSize = 1e3, maxTries = 1e3 }) {
if (maxTries < 2) throw new Error("`maxTries` must be >= 2");
const textMeasurer = await getTextMeasurer(text, font, maxWidth, maxHeight, lineHeight);
for (let tries = 1, lower = minFontSize, upper = maxFontSize; tries < maxTries; ++tries) {
const searchCutoffThreshold = Math.min(1, lower);
if (upper - lower <= searchCutoffThreshold) return Math.floor(lower);
const sizeCandidate = Math.floor(lower + (upper - lower) / 2);
const doesFit = await textMeasurer.doesSizeFit(sizeCandidate);
if (doesFit) lower = sizeCandidate;
else upper = sizeCandidate;
}
throw new Error(`Could not find a valid font size in ${maxTries - 1} attempts. Giving up. Please try again after constraining the search space, e.g. by restricting the min/max font size difference.`);
}
//#endregion
export { findLargestUsableFontSize };
//# sourceMappingURL=fitText.js.map