@altano/satori-fit-text
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

satori-fit-text

Calculate the largest text font size that will fit a bounding box, without a web browser. Works anywhere Satori does, e.g. Node.js, web browser, Vercel edge runtime, etc.

Demo

Installation

# Using NPM
npm install @altano/satori-fit-text
# Using Yarn
yarn add @altano/satori-fit-text
# Using PNPM
pnpm add @altano/satori-fit-text

Basic Example

import { findLargestUsableFontSize, type Font } from "@altano/satori-fit-text";

async function getInter(): Promise<Font> {
  const interSemiBoldBuffer = await fetch(`https://cdn.jsdelivr.net/npm/@fontsource/inter@5.0.17/files/inter-latin-600-normal.woff`).then((res) => res.arrayBuffer());

  const font = {
    name: "Inter",
    data: interSemiBoldBuffer,
    weight: 600,
  };
}

const largestUsableFontSize = await findLargestUsableFontSize({
  lineHeight: 1,
  font: await getFont(),
  text: "Some text I want to be as big as possible",
  maxWidth: 1136,
  maxHeight: 429,
});

console.log(largestUsableFontSize);

Example Uses

Implementation

The library tries various font sizes until it finds the ideal one that works. Each iteration is tested by generating an SVG with Satori and calculating the bounding box of the SVG.

Performance

The font size search is a binary search between 1 and 1000 with O(log maxFontSize-minFontSize) runtime, or a default of O(log 1000). You can improve performance by restricting the search space by reducing the difference between minFontSize and maxFontSize, which reduces the number of guesses.

If you're doing something like producing Open Graph cards then you probably don't need to worry about performance.

Package Sidebar

Install

npm i @altano/satori-fit-text

Weekly Downloads

32

Version

0.1.4

License

ISC

Unpacked Size

767 kB

Total Files

21

Last publish

Collaborators

  • altano