From 79f1583663e5621d65f04966deb4e7eb5f32a147 Mon Sep 17 00:00:00 2001 From: nondefault Date: Thu, 16 Nov 2023 15:35:15 -0800 Subject: [PATCH] improve font sizing --- src/lib/generate-og-image.tsx | 52 ++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/src/lib/generate-og-image.tsx b/src/lib/generate-og-image.tsx index 7ea6e49..f3559e0 100644 --- a/src/lib/generate-og-image.tsx +++ b/src/lib/generate-og-image.tsx @@ -14,31 +14,61 @@ function loadDataUrl(relPath: string, mimeType: string): string { return `data:${mimeType};base64,${base64Data}`; } +/** + * A heuristic for choosing a font size to fill a box (assuming perfectly even line wrapping) + * @returns a size in pixels to roughly fill the box + */ +function maximizeFontSize({ + text, + width, + height, +}: { + text: string; + width: number; + height: number; +}): number { + let lines = 1; + let size = Math.min(width / text.length, height); + while (size * (lines + 1) < height) { + lines += 1; + size = Math.min(width / (text.length / lines), height); + } + return size; +} + export async function generateOgImage({ title, }: { title: string; }): Promise { + const width = 1200; + const height = 630; + const titleFontSize = `${maximizeFontSize({ + text: title, + width, + height: height / 2, + })}px`; + return new ImageResponse( (
{title} @@ -57,8 +89,8 @@ export async function generateOgImage({
), { - width: 1200, - height: 630, + width, + height, fonts: [ { name: 'font-serif',