|
| 1 | +--- |
| 2 | +group: Examples |
| 3 | +--- |
| 4 | + |
| 5 | +# Social cards for static sites |
| 6 | + |
| 7 | +A link preview (the Open Graph image) is the picture a chat app or social network shows when someone shares a page. |
| 8 | +Generating one per page usually means a headless browser or a hosted service. ImageScript renders text, gradients and |
| 9 | +photos in plain TypeScript, so a card is a short build script: no browser, no native module, the same pixels on every |
| 10 | +machine, and nothing to install in CI besides `npm install`. |
| 11 | + |
| 12 | +This is a card the script made: |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +## The script |
| 17 | + |
| 18 | +This script writes one 1200×630 card for every Markdown post in `content/posts`, using the `title`, `description` and |
| 19 | +`date` from the front matter. Save it as `scripts/social-cards.mjs`, put a font in `fonts/` (any TrueType, OpenType or |
| 20 | +WOFF file; a variable font such as Inter gives the bold weight from one file) and run `node scripts/social-cards.mjs`. |
| 21 | + |
| 22 | +```js |
| 23 | +// One 1200×630 link preview per Markdown post: content/posts/<slug>.md -> public/og/<slug>.png |
| 24 | +import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'; |
| 25 | +import { Image } from 'imagescript'; |
| 26 | + |
| 27 | +const postsDir = 'content/posts'; |
| 28 | +const outDir = 'public/og'; |
| 29 | +const site = 'example.com'; |
| 30 | + |
| 31 | +// any TrueType, OpenType or WOFF font; a variable font gives the bold weight from the same file |
| 32 | +const font = await readFile('fonts/Inter.ttf'); |
| 33 | +const width = 1200; |
| 34 | +const height = 630; |
| 35 | +const pad = 72; |
| 36 | + |
| 37 | +// the background is the same for every card: make it once |
| 38 | +const stops = [0x141821ff, 0x2a2350ff]; |
| 39 | +const background = Image.linearGradient(width, height, { stops, angle: 135 }); |
| 40 | + |
| 41 | +// front matter: the `key: value` lines between the two `---` lines at the top |
| 42 | +function frontMatter(source) { |
| 43 | + const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(source)?.[1] ?? ''; |
| 44 | + const pairs = block.split(/\r?\n/).map((line) => /^(\w+):\s*(.*)$/.exec(line)).filter(Boolean); |
| 45 | + return Object.fromEntries(pairs.map(([, key, value]) => [key, value.replace(/^(["'])(.*)\1$/, '$2')])); |
| 46 | +} |
| 47 | + |
| 48 | +async function card({ title, description, date }) { |
| 49 | + const image = background.clone(); |
| 50 | + const footer = await Image.renderText(`${site}${date ? ` · ${date}` : ''}`, { |
| 51 | + font, size: 28, color: 0xf28db2ff, variations: { weight: 600 }, |
| 52 | + }); |
| 53 | + const summary = description && await Image.renderText(description, { |
| 54 | + font, size: 32, color: 0xb8bfd0ff, width: width - pad * 2, height: 100, |
| 55 | + }); |
| 56 | + // the title in the largest size that leaves room for the summary and the footer |
| 57 | + const room = height - pad * 2 - footer.height - (summary ? summary.height + 28 : 0) - 28; |
| 58 | + let heading; |
| 59 | + for (let size = 72; size >= 40; size -= 4) { |
| 60 | + heading = await Image.renderText(title, { |
| 61 | + font, size, color: 0xffffffff, variations: { weight: 800 }, width: width - pad * 2, |
| 62 | + }); |
| 63 | + if (heading.height <= room) break; |
| 64 | + } |
| 65 | + image.composite(heading, { x: pad, y: pad }); |
| 66 | + if (summary) image.composite(summary, { x: pad, y: pad + heading.height + 28 }); |
| 67 | + image.composite(footer, { x: pad, y: height - pad - footer.height }); |
| 68 | + // compression level 1 is several times faster than the default, and only a little larger for flat graphics |
| 69 | + return image.encodePNG({ compression: 1 }); |
| 70 | +} |
| 71 | + |
| 72 | +await mkdir(outDir, { recursive: true }); |
| 73 | +for (const file of (await readdir(postsDir)).filter((name) => name.endsWith('.md'))) { |
| 74 | + const slug = file.slice(0, -3); |
| 75 | + const target = `${outDir}/${slug}.png`; |
| 76 | + // keep the cards that are newer than their post |
| 77 | + const [post, existing] = await Promise.all([stat(`${postsDir}/${file}`), stat(target).catch(() => null)]); |
| 78 | + if (existing && existing.mtimeMs > post.mtimeMs) continue; |
| 79 | + const data = frontMatter(await readFile(`${postsDir}/${file}`, 'utf8')); |
| 80 | + const { title = slug, description, date } = data; |
| 81 | + await writeFile(target, await card({ title, description, date })); |
| 82 | + console.log('wrote', target); |
| 83 | +} |
| 84 | +``` |
| 85 | +
|
| 86 | +A card takes about 30 milliseconds (Node.js 26 on a 2018 laptop CPU), so a site with hundreds of posts is done in |
| 87 | +seconds. Cards that are newer than their post are skipped, and the title shrinks until it fits the card. |
| 88 | +
|
| 89 | +## Using it |
| 90 | +
|
| 91 | +Run the script before your site's build, for example `"build": "node scripts/social-cards.mjs && <your build>"`, and |
| 92 | +point every page at its card: |
| 93 | +
|
| 94 | +```html |
| 95 | +<meta property="og:image" content="https://example.com/og/hello-world.png"> |
| 96 | +<meta property="og:image:width" content="1200"> |
| 97 | +<meta property="og:image:height" content="630"> |
| 98 | +<meta name="twitter:card" content="summary_large_image"> |
| 99 | +``` |
| 100 | +
|
| 101 | +## Changing the design |
| 102 | +
|
| 103 | +- **A cover photo and an avatar:** decode them with {@link Image.decode}, size them with {@link Image.resize | resize} |
| 104 | + (`fit: 'cover'`), round them with {@link Image.roundCorners | roundCorners} or {@link Image.cropCircle | cropCircle} |
| 105 | + and place them with {@link Image.composite | composite}. The [Playground](https://try.imagescript.dev/) has this as the |
| 106 | + example "Open Graph Card", with a shadow and a glow behind the cover. |
| 107 | +- **Other scripts and emoji:** `font` takes a list; every character comes from the first font that has it, for example |
| 108 | + `font: [inter, notoArabic, notoEmoji]`. A character that no font has is drawn as a box. |
| 109 | +- **A logo:** render an SVG once with {@link Image.renderSVG} and composite it onto every card. |
| 110 | +
|
| 111 | +## At request time |
| 112 | +
|
| 113 | +The same `card()` function works in a request handler on any runtime that runs ImageScript. Mind the CPU time your |
| 114 | +platform allows per request: a card like this one needs about 30 milliseconds, which is more than the 10 milliseconds of |
| 115 | +Cloudflare Workers' free plan. For a static site, generating the cards at build time has no such limit. |
0 commit comments