简单来说
一张日食前天文讲座的海报。示例演示怎样以页面边缘或另一个元素为基准,确定每个元素的位置。
成品一览
一个虚构的天文俱乐部为2027年8月2日日全食之前的四个周四晚间讲座做的海报。群青色天空填满A3页面的上方三分之二。右侧,黑色的月亮遮住一轮被裁切线切掉一块的柠檬黄太阳,一圈用代码画出的日冕在两者身后散开。标题The Shadow Returns用120 pt的Funnel Display,立在导语之上,位于天空底部。地平线下,四个蓝色日期领起各场讲座,小字说明分两栏排在一条蓝色色带之上。每个元素都挂在出血、页面、所在设计槽或另一个元素上,偏移量从那里算起。第二张重复这张海报,在每个元素的框以及页眉、页脚容器周围画一圈粉色边框,并给十三个元素加上标记,印出各自的定位方式。
这道食谱解答
- 怎样把设计元素相对页面、出血边或彼此定位,而不是用坐标?
- 怎样给每一页加水印、背景底色或装饰图片?
简短回答
const SKY = 272; // mm from the trim's top edge to the horizon, the sky's lower edge
const INSET = BLEED + MARGIN; // from the bleed's edge to the text's edge
const AIR = 14; // mm between the standfirst and the horizon
const poster = () => ({ enabled: true, slot: { elements: [ // array order is paint order
// 'bleed' and 'page' are frames of the sheet; 'container' would be this heading's own box.
{ kind: 'box', id: 'sky', style: { backgroundColor: col('sky') }, // no width: fills the bleed
placement: at('bleed', 'top-left', 0, 0, { height: mm(BLEED + SKY) }) },
...eclipse(), // the Sun hangs from the trim's corner, the Moon and the corona from the Sun
// The headline stands on the horizon and grows upwards: 'above' puts an element's
// bottom-left corner on the top-left corner of its anchor, so a longer title lifts the kicker.
text('deck', '{attr.deck}', FACE.deck, { ...at('#sky', 'align-bottom', INSET, -AIR),
size: { maxWidth: mm(153) } }), // shrink-wraps its lines, but wraps at 153 mm
text('title', '{titleText}', FACE.title, at('#deck', 'above', 0, -9)), // breaks at the \\
text('kicker', '{attr.kicker}', FACE.kicker, at('#title', 'above', 0, -7)),
...programme(), // four columns chained off the horizon
] } }); // hook-up: headings.levels[0] = { span: 'page', breakBefore, advancedDesign: poster() }
// {titleText} is the heading's text; each {attr.*} is written on its line in content.md.
用料
- 还用到
- 出血与裁切标记
- 类型
- Funnel Display, Funnel Sans, Martian Mono(SIL OFL 1.1)
- 素材
- 无:所有图片都用代码绘制
做法
#1 · 把两个元素钉在页面上,其余挂在它们身上
代码见上面的简短回答。其中anchor.to指明元素挂在什么上:'bleed'和'page'是页面的两个框(page.cutLines关闭时二者是同一个框),'container'是设计槽自己的框,'#id'是另一个元素(元素定位)。没有宽度的框会一直伸到其参照框的另一侧边缘,所以天空从左到右填满出血。相对天空定位的元素从天空的左边缘量起,也就是出血的左边缘,所以导语的x取INSET,即18 mm。标题区从天空下边缘往上搭:'align-bottom'让导语框的底边位于该边缘之上AIR(14 mm)处,'above'让每个元素的底边落在下面那个元素的顶边上,所以标题多占几行时,会把眉题往上顶,而不会压住导语。设计区域下方,小字说明从最低元素(主讲人那一行)之下至少3.2 mm处的第一条16 pt网格线开始;这3.2 mm是标题默认的下外边距。
#2 · 把月亮和日冕挂在太阳上
const SUN = 150; // mm across; the Moon is drawn the same size
const CORONA = 300; // mm, the square picture of the corona
const HALO = (CORONA - SUN) / 2; // how far the corona reaches past the Sun on every side
const BITE = { x: 2, y: 2.5 }; // mm the Moon sits off the Sun: a sliver is left at upper left
const disc = (id, colour, placement) => ({ kind: 'box', id, placement: { ...placement,
size: square(SUN) }, style: { backgroundColor: col(colour), borderRadius: mm(SUN / 2) } });
const eclipse = () => [
{ kind: 'image', id: 'corona', resourceId: 'corona', // listed before the discs: painted behind
placement: at('#sun', 'align-top', -HALO, -HALO, square(CORONA)) },
disc('sun', 'sun', at('page', 'top-right', 30, 25)), // 30 mm of it past the right edge
disc('moon', 'ink', at('#sun', 'align-top', BITE.x, BITE.y)),
];
太阳是唯一钉在页面(成品框)上的元素。从'top-right'角量起,正的x会越过右边缘,所以圆盘有30 mm被切掉。月亮和日冕用'align-top'挂在太阳上,移动太阳,两者跟着动。它们的偏移量从太阳的左上角算起:月亮向右2 mm、向下2.5 mm,在左上方露出一弯太阳;日冕向左上方退HALO(75 mm),使它300 mm的正方形以150 mm的圆盘为中心。日冕是一个图像元素,尺寸取其框的大小(图像元素),并在列表中排在两个圆盘之前,所以画在它们后面。
#3 · 把各场讲座串成栏
const GUT = 7; // mm between the evenings, and between the two columns of text under them
const COL = (A3.width - 2 * MARGIN - 3 * GUT) / 4; // four columns across the text width: 60 mm
const DROP = 12; // mm from the horizon to the dates
const programme = () => [1, 2, 3, 4].flatMap((n) => [
text(`day${n}`, `{attr.d${n}}`, FACE.day, n === 1
? at('#sky', 'below', INSET, DROP, wide(COL)) // the first date hangs from the horizon
: at(`#day${n - 1}`, 'right-of', GUT, 0, wide(COL))), // the others from the one before
text(`talk${n}`, `{attr.t${n}}`, FACE.talk, at(`#day${n}`, 'below', 0, 3, wide(COL))),
text(`who${n}`, `{attr.s${n}}`, FACE.who, at(`#talk${n}`, 'below', 0, 2.5, wide(COL))),
]);
每个日期、讲座题目和主讲人行都有固定的size.width,值为COL;'right-of'加上GUT把下一个日期放到右边一栏。没有宽度时,日期会收缩到数字本身的宽度(“8”宽17 mm),于是“15”会紧跟其后7 mm开始,每个讲座题目也会排成一行伸进下一栏。COL把正文宽度分成四份,栏间距同下方两栏小字一样是7 mm,这样小字的第二栏正好位于22之下。每个讲座题目'below'挂在其日期下,每行主讲人挂在其题目下,所以一个题目折成三行时,只会把它自己的主讲人往下推。
#4 · 把色带放进页脚,每页都印
const MARK = 10; // mm, the club's mark
const PAD = (FOOT - MARK) / 2; // centres the mark in the bottom margin
const markTall = { height: mm(MARK) }; // as tall as the mark: the line is centred on it
const footer = { elements: [
{ kind: 'box', id: 'band', style: { backgroundColor: col('sky') }, // the bottom margin, bled
placement: at('bleed', 'bottom-left', 0, 0, { height: mm(BLEED + FOOT) }) },
// The container runs from the text down to the trim: 'bottom-*' counts up, 'top-*' down.
{ kind: 'image', id: 'mark', resourceId: 'mark',
placement: at('container', 'bottom-left', 0, -PAD, square(MARK)) },
text('club', '{attr.club}', FACE.foot, at('#mark', 'right-of', 3, 0, markTall)),
text('free', '{attr.free}', FACE.foot, at('container', 'top-right', 0, PAD, markTall)),
] };
凡是每页都要印的东西,比如这条色带,都放进页眉或页脚设计槽;带有自己页眉或页脚的标题样式,会在其所属章节的页面上替换这个设计槽。guides样式的页脚重复了这四个元素,并加上边框和标记,所以色带和标志在两张上都会印出。页脚的容器就是下页边距,从正文一直到裁切线:'bottom-left'从裁切线往上量,'top-right'从正文往下量,标志的−10和“Free entry”一行的+10落在色带中间同一条10 mm宽的带上(页眉和页脚)。页脚在正文之后绘制,不占用正文空间,所以FOOT同时设定下页边距和色带高度,色带也就不会碰到上面的文字。
#5 · 用同一份配置画出结构线
const GUIDE = { borderColor: col('guide'), borderWidth: pt(1) };
const signed = ({ value }) => `${value < 0 ? '−' : '+'}${Math.abs(value)}`; // all offsets in mm
const describe = ({ id, placement: { anchor: { to, edge }, offset = {} } }) => [`#${id}`,
`${edge} ${to}`, // the two words of anchor: { to, edge }
['x', 'y'].filter((k) => offset[k]?.value).map((k) => `${k} ${signed(offset[k])}`).join(' '),
].filter(Boolean).join(' · ');
// A border never changes an element's size (padding does), so each frame traces its box.
// An image or a rounded box gets a square frame of its size, hung from its top-left corner.
const frame = (el) => (el.kind === 'text' ? [{ ...el, box: { ...el.box, ...GUIDE } }]
: el.kind === 'box' && !el.style.borderRadius ? [{ ...el, style: { ...el.style, ...GUIDE } }]
: [el, { kind: 'box', id: `${el.id}-box`, style: GUIDE,
placement: at(`#${el.id}`, 'align-top', 0, 0, el.placement.size) }]);
const tag = (el, [edge, x = 0, y = 0, note]) => text(`${el.id}-tag`, note ?? describe(el),
face('Martian Mono', 8.5, 500, 'ink', { box: { backgroundColor: col('guide'),
padding: { top: pt(1.6), bottom: pt(1.2), left: pt(3), right: pt(3) } } }),
at(`#${el.id}`, edge, x, y));
const guides = (elements, tags) => [...elements.flatMap(frame),
...elements.filter((el) => tags[el.id]).map((el) => tag(el, tags[el.id]))];
const container = (id) => ({ kind: 'box', id, style: GUIDE, // the slot's own box, drawn
placement: at('container', 'top-left', 0, 0, { width: 'fill', height: 'fill' }) });
const TAGS = { // where each tag sits against its element: [edge, x, y, text]
sky: ['align-bottom', INSET, -3], corona: ['align-bottom', 90, -2], sun: ['above'],
moon: ['below', 20, 2], kicker: ['above'], title: ['above'], deck: ['above'],
day1: ['above', 0, -6], day2: ['above'], who1: ['below'],
mark: ['above', 0, -2], club: ['above', 69, -2], free: ['above', -30, -2],
header: ['align-bottom', 0, -2, t({ en: 'header container', es: 'contenedor de la cabecera' })],
footer: ['align-bottom', 0, -2, t({ en: 'footer container', es: 'contenedor del pie' })],
};
guides()遍历海报的所有元素。文本元素在其框上加边框,方形框在其样式上加边框;两者都不会移动任何东西,因为只有内边距会让框变大。图像或圆盘则得到一个与自身同尺寸、挂在其左上角的方框,这样月亮和日冕所挂的太阳左上角也画了出来。每个标记是一段挂在所属元素上的文本,由describe()根据该元素自己的placement写成,因此标记不会与它所标注的配置不一致。第二个标题上的{style="guides"}引入这套设计以及它自己的页眉和页脚(标题样式)。没有宽度的标记只能用它的锚点到容器右边缘之间的空间,所以#free的标记从其文本左侧30 mm处开始。内容continuation中的pageIndexOffset: 1让海报成为左页,查看器因此把两张并排显示。
完整食谱
// ═══ Postext Cookbook · Nº 029 · Anchoring cheat sheet: a poster built from chained elements ═══
// https://postext.dev/en/cookbook/anchoring-cheat-sheet
// Code: MIT · Text: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: Funnel Display, Funnel Sans, Martian Mono (SIL OFL 1.1) · Needs postext ≥ 1.34.0
// An A3 poster whose elements hang from the bleed, the page, their slot or one another, never
// from coordinates; the second sheet is the same poster with each element framed and tagged.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'anchoring-cheat-sheet';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = {
ink: '#0b0b0c', // text, and the Moon
sky: '#1b3bff', // the sky, the foot band and the dates
sun: '#ffe53b', // the Sun and the kicker
paper: '#ffffff', // type on the sky
muted: '#5c5f66', // speakers and the colophon
guide: '#ff2d9b', // frames and tags on the construction sheet
};
// col(id): a colour linked to its palette entry, so a swapped palette recolours the sheet.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
{ id: 'main-color', name: 'sky (defaults)', value: { hex: palette.sky, model: 'hex' } },
];
const A3 = { width: 297, height: 420 }; // mm, the trim
const MARGIN = 18; // mm at the top and sides: the body's edges, and the header container's
const FOOT = 30; // mm, the bottom margin: the footer container and its band
const BLEED = 0; // mm; 3 for the printer, which switches on page.cutLines below
// at(): a placement. Offsets are distances from the anchor point, never page coordinates.
const at = (to, edge, x = 0, y = 0, size) => ({ anchor: { to, edge },
offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });
const wide = (w) => ({ width: mm(w) }); // fixed, so a text is as wide as its column
const square = (d) => ({ width: mm(d), height: mm(d) });
// Design text is centred by default, and in a footer it is cut with '…': these wrap, set left.
const text = (id, content, face, placement) => ({ kind: 'text', id, content, overflow: 'wrap',
align: 'left', ...face, placement });
const face = (fontFamily, size, fontWeight, colour, more) => ({ fontFamily, fontSize: pt(size),
fontWeight, color: col(colour), ...more });
const caps = (tracking) => ({ letterSpacing: pt(tracking), textTransform: 'uppercase' });
const FACE = { // lineHeight as a multiple of each size
kicker: face('Martian Mono', 12, 500, 'sun', caps(1.8)),
title: face('Funnel Display', 120, 800, 'paper', { lineHeight: 0.86 }),
deck: face('Funnel Sans', 22, 400, 'paper', { lineHeight: 1.22 }),
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#加3 mm出血和裁切标记
把BLEED设为3 mm会打开裁切线,并把天空和底部色带推进它们所挂的出血3 mm,而INSET让文字留在页边距上;太阳、月亮和日冕挂在页面上,而页面画出的一切都按出血范围裁切,所以太阳止于成品尺寸外3 mm处,出血以外只留裁切线。
-const BLEED = 0; // 毫米;交付印刷时设为3,下面的page.cutLines随之打开
+const BLEED = 3; // 毫米;交付印刷时设为3,下面的page.cutLines随之打开#抬高地平线
从SKY减去20 mm会抬高天空的边缘,导语、标题、眉题和讲座的十二段文字随之上移,小字说明也从更高的一条网格线开始;太阳挂在页面上,所以第二处改动把它同样抬高20 mm,否则Shadow的“w”会碰到月牙。
-const SKY = 272; // 从裁切框上边缘到地平线(即天空下边缘)的毫米数
+const SKY = 252; // 从裁切框上边缘到地平线(即天空下边缘)的毫米数
- disc('sun', 'sun', at('page', 'top-right', 30, 25)), // 有30 mm越过右边缘
+ disc('sun', 'sun', at('page', 'top-right', 30, 5)), // 有30 mm越过右边缘常见问题
- 在pen里,循环锚点和悬空锚点都不会有任何报告。沙盒的“检查”面板会列出页眉、页脚、篇名页和各级标题中的这类问题,但不检查
guides这样的标题样式。钉在一个不存在的#id上的元素会相对容器定位:'below'这类元素边退回到容器左上角(偏移量照算),'top-right'这类容器边也退回到那个角。出现循环时,其中一个元素同样这样退回,其余元素再从它串下去。 'align-left'和'align-top'落在同一点:两者都把元素的左上角放在锚点的左上角。- 边框以框的边缘为中线绘制,所以每条1 pt的粉色边框会超出所描的框0.5 pt,尽管配置文档说描边画在框内。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- Funnel Display (SIL OFL 1.1) · Funnel Sans (SIL OFL 1.1) · Martian Mono (SIL OFL 1.1)


