跳到正文
网页珍奇柜Web Curio

不碰 DOM 的文字排版引擎

Pretext,Cheng Lou & contributors,2026 年

正在布展…

原作直展:这是 Cheng Lou & contributors 的原始作品,按 MIT(示范文本为《爱丽丝漫游奇境》开篇,公有领域) 许可证收录(版本 4a98f37)。作者的演示页需要用 Bun 构建,未能收录;这里收录 npm 1.0.0 原版库,配一张本柜写的演示:一篇文章每帧绕着三颗漂浮的球重新断行,全程不读 DOM。可以拖动小球,右下角显示每帧排版耗时。 许可证全文 · 收录说明

它是怎么做的

  1. 第 1 步预先用 canvas measureText 缓存字形/片段宽度。
  2. 第 2 步自己实现断行(含 Knuth-Plass 两两比较)与连字符。
  3. 第 3 步障碍物(圆、图片)被转成每行可用的水平区间,文字逐行填入。
  4. 第 4 步「可变字体 ASCII」演示用测得的比例字宽代替等宽格,让字符画更细腻。

复刻配方

一段技术配方,可以直接交给 AI 编程助手,也可以自己照着写。想指定技术栈、位置和性能预算,就把它加入实现方案。

Cache advance widths of words and graphemes using an offscreen canvas measureText call per font. Implement a line breaker that, for each line's y position, asks an obstacle function for the free horizontal intervals (subtracting circles or rectangles) and greedily packs words into them. Re-run layout every animation frame as obstacles move, then position absolutely placed spans or draw with fillText. For the ASCII variant, choose glyphs per cell by both brightness and measured width so a proportional font fills cells without gaps.

档案

能不能拿来用

原作以 MIT 许可开源:可以阅读源码学习,按许可证条款使用;在自己的项目里引用时保留原作者署名。

性能开销

视觉强度

实现难度

尺度为策展判断(1 到 5),用于比较和推荐。

核实记录:Opened the demo index (10 demos: Accordion, Bubbles, Dynamic Layout, Variable Typographic ASCII, Editorial Engine, etc.); read LICENSE file in repo (MIT, 2026 Pretext contributors).