Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

tablePng.ts

661 lines24.1 KB

1import { type Canvas2D, createCanvas } from "~/lib/imageCanvas";
2import { encodeCanvas } from "~/lib/imageCompression";
3​
4/*
5 * Paints a rendered table onto a canvas from the layout the browser has already computed: one
6 * read pass over the table (computed styles and client rects, no DOM writes), then plain canvas
7 * draws and an asynchronous PNG encode. Nothing is cloned, no styles are inlined, and nothing is
8 * laid out a second time, as an SVG <foreignObject> snapshot would.
9 */
10​
11/** Space around the table, in CSS pixels, so the outer columns are not cut at the image edge. */
12const MARGIN = 16;
13const MAX_SCALE = 3;
14/** iOS Safari's canvas area limit. A larger table is drawn at a lower scale to fit. */
15const MAX_CANVAS_AREA = 16_777_216;
16const MAX_CANVAS_SIDE = 16_384;
17const ELLIPSIS = "…";
18/** Stands in for "no clip" on the axis an `overflow-x`/`overflow-y` box leaves visible. */
19const UNBOUNDED = 1e6;
20const XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";
21​
22interface Box {
23 readonly x: number;
24 readonly y: number;
25 readonly width: number;
26 readonly height: number;
28​
29type DrawOp =
30 | { kind: "fill"; box: Box; color: string; radius: number; alpha: number }
31 | { kind: "stroke"; box: Box; color: string; width: number; radius: number; alpha: number }
32 | { kind: "mark"; box: Box; dash: boolean; alpha: number }
33 | {
34 kind: "text";
35 text: string;
36 x: number;
37 y: number;
38 font: string;
39 color: string;
40 direction: CanvasDirection;
41 letterSpacing: string;
42 alpha: number;
43 }
44 | { kind: "image"; box: Box; image: Promise<CanvasImageSource | null>; alpha: number }
45 | { kind: "clip"; box: Box }
46 | { kind: "unclip" };
47​
48interface Ellipsis {
49 /** The content edge that text must not cross. */
50 readonly right: number;
51 done: boolean;
53​
54interface Scope {
55 readonly style: CSSStyleDeclaration;
56 readonly alpha: number;
57 /** Inside an inline-level box: painted with the text, after every block background. */
58 readonly inline: boolean;
59 /** Decorations propagate to descendant text without being inherited in computed style. */
60 readonly decorations: readonly CSSStyleDeclaration[];
61 readonly ellipsis: Ellipsis | null;
63​
64const PRESERVED_SPACES = /^(?:pre|pre-wrap|break-spaces)$/;
65​
66function isTransparent(color: string): boolean {
67 return color === "transparent" || /^rgba\(.*,\s*0\)$/.test(color);
69​
70function isOpaque(color: string): boolean {
71 return !color.startsWith("rgba(") && !color.includes("/");
73​
74function canvasFont(style: CSSStyleDeclaration): string {
75 // Canvas fonts take a keyword for oblique, not an angle.
76 const fontStyle = style.fontStyle.startsWith("oblique") ? "oblique" : style.fontStyle;
77 return `${fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
79​
80function transformText(text: string, transform: string): string {
81 if (transform === "uppercase") return text.toUpperCase();
82 if (transform === "lowercase") return text.toLowerCase();
83 if (transform === "capitalize")
84 return text.replace(
85 /(^|\s)(\p{L})/gu,
86 (_, space: string, letter: string) => space + letter.toUpperCase(),
87 );
88 return text;
90​
91function cornerRadius(value: string, box: Box): number {
92 const radius = Number.parseFloat(value) || 0;
93 return value.endsWith("%") ? (Math.min(box.width, box.height) * radius) / 100 : radius;
95​
96/** A cross-origin image would taint the canvas and fail the whole encode, so test it alone. */
97function isReadable(image: HTMLImageElement): boolean {
98 const probe = createCanvas(1, 1, "srgb");
99 try {
100 probe?.context.drawImage(image, 0, 0, 1, 1);
101 probe?.context.getImageData(0, 0, 1, 1);
102 return true;
103 } catch {
104 return false;
105 }
107​
108/** Replays draw ops; `images[i]` is the decoded source for an image op at index `i`. */
109function paintOps(
110 context: Canvas2D["context"],
111 scale: number,
112 ops: readonly DrawOp[],
113 images: readonly (CanvasImageSource | null)[],
114): void {
115 context.textBaseline = "alphabetic";
116 context.textAlign = "left";
117 // Snaps hard edges to device pixels so 1px rules stay crisp at any scale.
118 const snap = (value: number) => Math.round(value * scale) / scale;
119 let font = "";
120 for (const [index, op] of ops.entries()) {
121 switch (op.kind) {
122 case "fill": {
123 context.globalAlpha = op.alpha;
124 context.fillStyle = op.color;
125 if (op.radius > 0) {
126 context.beginPath();
127 context.roundRect(op.box.x, op.box.y, op.box.width, op.box.height, op.radius);
128 context.fill();
129 } else {
130 const x = snap(op.box.x);
131 const y = snap(op.box.y);
132 context.fillRect(
133 x,
134 y,
135 Math.max(snap(op.box.x + op.box.width) - x, 1 / scale),
136 Math.max(snap(op.box.y + op.box.height) - y, 1 / scale),
137 );
138 }
139 break;
140 }
141 case "stroke": {
142 const inset = op.width / 2;
143 context.globalAlpha = op.alpha;
144 context.strokeStyle = op.color;
145 context.lineWidth = op.width;
146 context.beginPath();
147 context.roundRect(
148 op.box.x + inset,
149 op.box.y + inset,
150 op.box.width - op.width,
151 op.box.height - op.width,
152 Math.max(op.radius - inset, 0),
153 );
154 context.stroke();
155 break;
156 }
157 case "mark": {
158 const { x, y, width: w, height: h } = op.box;
159 // The fill's color can be any CSS color; reading it back is the simplest way to pick contrast.
160 const p = context.getImageData((x + w / 2) * scale, (y + h / 2) * scale, 1, 1).data;
161 context.save();
162 context.globalAlpha = op.alpha;
163 context.strokeStyle = p[0]! * 299 + p[1]! * 587 + p[2]! * 114 > 165_000 ? "#000" : "#fff";
164 context.transform(w, 0, 0, h, x, y);
165 context.lineWidth = Math.max(1.5 / Math.min(w, h), 0.14);
166 context.lineCap = context.lineJoin = "round";
167 context.stroke(new Path2D(op.dash ? "M.25 .5H.75" : "M.24 .52L.43 .71L.76 .31"));
168 context.restore();
169 break;
170 }
171 case "text": {
172 context.globalAlpha = op.alpha;
173 // Parsing a font string is the costly part of a text draw; most runs share one.
174 if (op.font !== font) {
175 font = op.font;
176 context.font = op.font;
177 }
178 context.fillStyle = op.color;
179 context.direction = op.direction;
180 context.letterSpacing = op.letterSpacing;
181 context.fillText(op.text, op.x, op.y);
182 break;
183 }
184 case "image": {
185 const image = images[index];
186 if (!image) break;
187 context.globalAlpha = op.alpha;
188 context.drawImage(image, op.box.x, op.box.y, op.box.width, op.box.height);
189 break;
190 }
191 case "clip": {
192 context.save();
193 context.beginPath();
194 context.rect(op.box.x, op.box.y, op.box.width, op.box.height);
195 context.clip();
196 break;
197 }
198 case "unclip": {
199 context.restore();
200 // A restore puts the saved font back too.
201 font = "";
202 break;
203 }
204 }
205 }
207​
208/** Copies a rendered `<table>` (and the backdrop behind it) into a PNG. */
209export async function renderTablePng(table: HTMLTableElement): Promise<Blob> {
210 // A detached table measures 0 x 0 and would copy an empty image over the clipboard.
211 if (!table.isConnected) throw new Error("The table left the page before it was drawn.");
212 const bounds = table.getBoundingClientRect();
213 const width = bounds.width + MARGIN * 2;
214 const height = bounds.height + MARGIN * 2;
215 const scale = Math.min(
216 Math.max(window.devicePixelRatio || 1, 1),
217 MAX_SCALE,
218 MAX_CANVAS_SIDE / width,
219 MAX_CANVAS_SIDE / height,
220 Math.sqrt(MAX_CANVAS_AREA / (width * height)),
221 );
222 // Rounding down keeps the canvas inside both caps; at most a pixel of margin is lost.
223 const surface = createCanvas(
224 Math.max(1, Math.floor(width * scale)),
225 Math.max(1, Math.floor(height * scale)),
226 "srgb",
227 );
228 if (!surface) throw new Error("A canvas is unavailable for the table image.");
229 const { canvas, context } = surface;
230​
231 const originX = bounds.left - MARGIN;
232 const originY = bounds.top - MARGIN;
233 const toBox = (rect: DOMRect): Box => ({
234 x: rect.left - originX,
235 y: rect.top - originY,
236 width: rect.width,
237 height: rect.height,
238 });
239​
240 // CSS paints block backgrounds and borders before inline content, whatever the tree order.
241 const blockOps: DrawOp[] = [];
242 const contentOps: DrawOp[] = [];
243 const objectUrls: string[] = [];
244 const range = document.createRange();
245 const fontMetrics = new Map<string, { ascent: number; descent: number }>();
246 let graphemes: Intl.Segmenter | undefined;
247​
248 const metricsFor = (font: string) => {
249 let metrics = fontMetrics.get(font);
250 if (!metrics) {
251 context.font = font;
252 const measured = context.measureText("x");
253 metrics = {
254 ascent: measured.fontBoundingBoxAscent,
255 descent: measured.fontBoundingBoxDescent,
256 };
257 fontMetrics.set(font, metrics);
258 }
259 return metrics;
260 };
261​
262 /** A text rect is its line box or its content area; the baseline sits the same in both. */
263 const baselineIn = (rect: DOMRect, font: string) => {
264 const { ascent, descent } = metricsFor(font);
265 return rect.top - originY + (rect.height - ascent - descent) / 2 + ascent;
266 };
267​
268 const paintBox = (rect: DOMRect, style: CSSStyleDeclaration, alpha: number, ops: DrawOp[]) => {
269 const box = toBox(rect);
270 if (box.width <= 0 || box.height <= 0) return;
271 const radius = cornerRadius(style.borderTopLeftRadius, box);
272 if (!isTransparent(style.backgroundColor)) {
273 ops.push({ kind: "fill", box, color: style.backgroundColor, radius, alpha });
274 }
275 const sides = (["Top", "Right", "Bottom", "Left"] as const).map((side) => ({
276 side,
277 width:
278 style[`border${side}Style`] === "none" || style[`border${side}Style`] === "hidden"
279 ? 0
280 : Number.parseFloat(style[`border${side}Width`]) || 0,
281 color: style[`border${side}Color`],
282 }));
283 const [first] = sides;
284 if (
285 radius > 0 &&
286 first &&
287 sides.every((side) => side.width === first.width && side.color === first.color)
288 ) {
289 if (first.width > 0 && !isTransparent(first.color)) {
290 ops.push({ kind: "stroke", box, color: first.color, width: first.width, radius, alpha });
291 }
292 return;
293 }
294 for (const { side, width: lineWidth, color } of sides) {
295 if (lineWidth <= 0 || isTransparent(color)) continue;
296 const edge: Box =
297 side === "Top"
298 ? { ...box, height: lineWidth }
299 : side === "Bottom"
300 ? { ...box, y: box.y + box.height - lineWidth, height: lineWidth }
301 : side === "Left"
302 ? { ...box, width: lineWidth }
303 : { ...box, x: box.x + box.width - lineWidth, width: lineWidth };
304 ops.push({ kind: "fill", box: edge, color, radius: 0, alpha });
305 }
306 };
307​
308 const pushText = (text: string, rect: DOMRect, scope: Scope) => {
309 const { style } = scope;
310 const font = canvasFont(style);
311 contentOps.push({
312 kind: "text",
313 text: transformText(text, style.textTransform),
314 x: rect.left - originX,
315 y: baselineIn(rect, font),
316 font,
317 color: style.color,
318 direction: style.direction === "rtl" ? "rtl" : "ltr",
319 letterSpacing: style.letterSpacing === "normal" ? "0px" : style.letterSpacing,
320 alpha: scope.alpha,
321 });
322 };
323​
324 /** A word broken across lines is drawn one line at a time. */
325 const pushBrokenWord = (node: Text, offset: number, word: string, scope: Scope) => {
326 graphemes ??= new Intl.Segmenter(undefined, { granularity: "grapheme" });
327 let run = "";
328 let runRect: DOMRect | null = null;
329 for (const { segment, index } of graphemes.segment(word)) {
330 range.setStart(node, offset + index);
331 range.setEnd(node, offset + index + segment.length);
332 const rect = range.getBoundingClientRect();
333 if (runRect && Math.abs(rect.top - runRect.top) < 1) {
334 run += segment;
335 continue;
336 }
337 if (runRect && run) pushText(run, runRect, scope);
338 run = segment;
339 runRect = rect;
340 }
341 if (runRect && run) pushText(run, runRect, scope);
342 };
343​
344 /** Draws the longest prefix that fits before the ellipsis, as `text-overflow` does. */
345 const pushTruncated = (node: Text, start: number, end: number, scope: Scope, right: number) => {
346 context.font = canvasFont(scope.style);
347 const limit = right - context.measureText(ELLIPSIS).width;
348 range.setStart(node, start);
349 let low = start;
350 let high = end;
351 let fitRight = 0;
352 while (low < high) {
353 const middle = Math.ceil((low + high) / 2);
354 range.setEnd(node, middle);
355 const rect = range.getBoundingClientRect();
356 if (rect.right <= limit) {
357 low = middle;
358 fitRight = rect.right;
359 } else {
360 high = middle - 1;
361 }
362 }
363 // Never end on half of a surrogate pair.
364 if (low > start && /[\uD800-\uDBFF]/.test(node.data[low - 1] ?? "")) low -= 1;
365 range.setEnd(node, Math.max(low, start + 1));
366 const lineRect = range.getBoundingClientRect();
367 const text = node.data.slice(start, low).trimEnd();
368 if (text) pushText(text, lineRect, scope);
369 else fitRight = lineRect.left;
370 const markRect = new DOMRect(fitRight, lineRect.top, 0, lineRect.height);
371 pushText(ELLIPSIS, markRect, scope);
372 };
373​
374 const pushDecorations = (rects: DOMRectList, scope: Scope) => {
375 if (!scope.decorations.length) return;
376 const font = canvasFont(scope.style);
377 const fontSize = Number.parseFloat(scope.style.fontSize) || 16;
378 const { ascent } = metricsFor(font);
379 for (const decoration of scope.decorations) {
380 const thickness = Math.max(
381 1,
382 Number.parseFloat(decoration.textDecorationThickness) || fontSize / 16,
383 );
384 const lines = decoration.textDecorationLine.split(" ");
385 for (const rect of rects) {
386 const baseline = baselineIn(rect, font);
387 for (const line of lines) {
388 const y =
389 line === "underline"
390 ? baseline + fontSize * 0.1
391 : line === "line-through"
392 ? baseline - fontSize * 0.28
393 : line === "overline"
394 ? baseline - ascent
395 : null;
396 if (y === null) continue;
397 contentOps.push({
398 kind: "fill",
399 box: {
400 x: rect.left - originX,
401 y: y - thickness / 2,
402 width: rect.width,
403 height: thickness,
404 },
405 color: decoration.textDecorationColor,
406 radius: 0,
407 alpha: scope.alpha,
408 });
409 }
410 }
411 }
412 };
413​
414 const visitText = (node: Text, scope: Scope) => {
415 const { style } = scope;
416 if (style.visibility !== "visible") return;
417 const data = node.data;
418 const start = data.search(/\S/);
419 if (start < 0) return;
420 const end = data.trimEnd().length;
421 range.setStart(node, start);
422 range.setEnd(node, end);
423 const rects = range.getClientRects();
424 const [firstRect] = rects;
425 if (!firstRect) return;
426 const { ellipsis } = scope;
427 if (ellipsis?.done) return;
428​
429 const slice = data.slice(start, end);
430 const text = PRESERVED_SPACES.test(style.whiteSpace)
431 ? slice
432 : slice.replace(/[ \t\n\r\f]+/g, " ");
433 // Chromium adds a rect for the part an ellipsis leaves visible, so a cut line has two.
434 if (
435 ellipsis &&
436 style.direction !== "rtl" &&
437 [...rects].some((rect) => rect.right > ellipsis.right + 0.5) &&
438 [...rects].every((rect) => Math.abs(rect.top - firstRect.top) < 1)
439 ) {
440 ellipsis.done = true;
441 pushTruncated(node, start, end, scope, ellipsis.right);
442 } else if (rects.length === 1 && !/[\t\n\r\f]/.test(text)) {
443 pushText(text, firstRect, scope);
444 } else {
445 // Wrapped lines, bidi runs, and tabs: place each word where layout put it.
446 for (const match of slice.matchAll(/\S+/g)) {
447 const wordStart = start + match.index;
448 range.setStart(node, wordStart);
449 range.setEnd(node, wordStart + match[0].length);
450 const wordRects = range.getClientRects();
451 const [wordRect] = wordRects;
452 if (!wordRect) continue;
453 if (wordRects.length === 1) pushText(match[0], wordRect, scope);
454 else pushBrokenWord(node, wordStart, match[0], scope);
455 }
456 }
457 pushDecorations(rects, scope);
458 };
459​
460 const visitSvg = (svg: SVGSVGElement, style: CSSStyleDeclaration, alpha: number) => {
461 const rect = svg.getBoundingClientRect();
462 if (rect.width <= 0 || rect.height <= 0) return;
463 const clone = svg.cloneNode(true) as SVGSVGElement;
464 // Sprite icons point at a shared <symbol> elsewhere in the document; carry it along.
465 const defs = document.createElementNS(svg.namespaceURI, "defs");
466 const copied = new Set<string>();
467 const pending = [...clone.querySelectorAll("use")];
468 for (let use = pending.pop(); use; use = pending.pop()) {
469 const href = use.getAttribute("href") ?? use.getAttributeNS(XLINK_NAMESPACE, "href");
470 const id = href?.startsWith("#") ? href.slice(1) : null;
471 if (!id || copied.has(id) || svg.querySelector(`#${CSS.escape(id)}`)) continue;
472 const target = document.getElementById(id);
473 if (!target) continue;
474 copied.add(id);
475 const copy = target.cloneNode(true) as Element;
476 defs.append(copy);
477 pending.push(...copy.querySelectorAll("use"));
478 }
479 if (copied.size) clone.prepend(defs);
480 if (!clone.hasAttribute("viewBox")) {
481 clone.setAttribute("viewBox", `0 0 ${rect.width} ${rect.height}`);
482 }
483 // Rasterize at the output scale so icons stay sharp.
484 clone.setAttribute("width", String(rect.width * scale));
485 clone.setAttribute("height", String(rect.height * scale));
486 clone.style.color = style.color;
487 const url = URL.createObjectURL(
488 new Blob([new XMLSerializer().serializeToString(clone)], { type: "image/svg+xml" }),
489 );
490 objectUrls.push(url);
491 const image = new Image();
492 image.src = url;
493 contentOps.push({
494 kind: "image",
495 box: toBox(rect),
496 image: image.decode().then(
497 () => image,
498 () => null,
499 ),
500 alpha,
501 });
502 };
503​
504 const visitImage = (image: HTMLImageElement, style: CSSStyleDeclaration, alpha: number) => {
505 if (!image.complete || image.naturalWidth === 0) return;
506 // Desktop serves workspace assets from the server's origin, not the page's; the server
507 // answers with CORS headers, so a CORS load of the same URL can be drawn.
508 let source: Promise<CanvasImageSource | null> = Promise.resolve(image);
509 if (!isReadable(image)) {
510 const corsImage = new Image();
511 corsImage.crossOrigin = "anonymous";
512 corsImage.src = image.currentSrc || image.src;
513 source = corsImage.decode().then(
514 () => (isReadable(corsImage) ? corsImage : null),
515 () => null,
516 );
517 }
518 const rect = image.getBoundingClientRect();
519 const inset = (side: "Top" | "Right" | "Bottom" | "Left") =>
520 (Number.parseFloat(style[`border${side}Width`]) || 0) +
521 (Number.parseFloat(style[`padding${side}`]) || 0);
522 const box = toBox(rect);
523 contentOps.push({
524 kind: "image",
525 box: {
526 x: box.x + inset("Left"),
527 y: box.y + inset("Top"),
528 width: box.width - inset("Left") - inset("Right"),
529 height: box.height - inset("Top") - inset("Bottom"),
530 },
531 image: source,
532 alpha,
533 });
534 };
535​
536 const visitElement = (element: Element, parent: Scope | null) => {
537 const style = getComputedStyle(element);
538 // Clipping hides visually hidden labels; other clip shapes are skipped too.
539 const clipRect = style.getPropertyValue("clip");
540 if (
541 style.display === "none" ||
542 style.clipPath !== "none" ||
543 (clipRect !== "" && clipRect !== "auto")
544 ) {
545 return;
546 }
547 const alpha = (parent?.alpha ?? 1) * (Number.parseFloat(style.opacity) || 0);
548 if (alpha <= 0) return;
549 const visible = style.visibility === "visible";
550 if (element instanceof SVGSVGElement) {
551 if (visible) visitSvg(element, style, alpha);
552 return;
553 }
554 // Shapes inside an SVG belong to its root; MathML still descends to its text.
555 if (element instanceof SVGElement) return;
556 if (element instanceof HTMLImageElement) {
557 if (visible) visitImage(element, style, alpha);
558 return;
559 }
560 const isCheckbox = element instanceof HTMLInputElement && element.type === "checkbox";
561 if (isCheckbox && style.appearance !== "none") {
562 const box = toBox(element.getBoundingClientRect());
563 const size = Math.min(box.width, box.height);
564 if (!visible || size <= 0) return;
565 const radius = Math.max(2, size * 0.18);
566 const dim = element.matches(":disabled") ? alpha * 0.5 : alpha;
567 if (element.checked || element.indeterminate) {
568 const color = style.accentColor !== "auto" ? style.accentColor : style.color;
569 contentOps.push({ kind: "fill", box, color, radius, alpha: dim });
570 contentOps.push({ kind: "mark", box, dash: element.indeterminate, alpha });
571 } else {
572 contentOps.push({ kind: "stroke", box, color: style.color, width: 1, radius, alpha: dim });
573 }
574 return;
575 }
576​
577 const inline = (parent?.inline ?? false) || style.display.startsWith("inline");
578 if (visible) {
579 for (const rect of element.getClientRects()) {
580 paintBox(rect, style, alpha, inline ? contentOps : blockOps);
581 }
582 }
583​
584 const clipsX = style.overflowX !== "visible";
585 const clipsY = style.overflowY !== "visible";
586 let clip: Box | null = null;
587 let ellipsis = parent?.ellipsis ?? null;
588 if (clipsX || clipsY) {
589 const box = toBox(element.getBoundingClientRect());
590 const left = box.x + (Number.parseFloat(style.borderLeftWidth) || 0);
591 const top = box.y + (Number.parseFloat(style.borderTopWidth) || 0);
592 const right = box.x + box.width - (Number.parseFloat(style.borderRightWidth) || 0);
593 const bottom = box.y + box.height - (Number.parseFloat(style.borderBottomWidth) || 0);
594 clip = {
595 x: clipsX ? left : -UNBOUNDED,
596 y: clipsY ? top : -UNBOUNDED,
597 width: clipsX ? right - left : UNBOUNDED * 2,
598 height: clipsY ? bottom - top : UNBOUNDED * 2,
599 };
600 // Both passes: a clipped block's descendants can be block-level boxes too.
601 blockOps.push({ kind: "clip", box: clip });
602 contentOps.push({ kind: "clip", box: clip });
603 if (clipsX && style.textOverflow === "ellipsis") {
604 const contentRight = right - (Number.parseFloat(style.paddingRight) || 0);
605 ellipsis = { right: contentRight + originX, done: false };
606 }
607 }
608 const scope: Scope = {
609 style,
610 alpha,
611 inline,
612 decorations:
613 style.textDecorationLine === "none"
614 ? (parent?.decorations ?? [])
615 : [...(parent?.decorations ?? []), style],
616 ellipsis,
617 };
618 for (const child of element.childNodes) {
619 if (child instanceof Element) visitElement(child, scope);
620 else if (child instanceof Text) visitText(child, scope);
621 }
622 if (clip) {
623 blockOps.push({ kind: "unclip" });
624 contentOps.push({ kind: "unclip" });
625 }
626 };
627​
628 // The backdrop: the nearest opaque background behind the table and every layer above it.
629 const backdrops: string[] = [];
630 for (let element = table.parentElement; element; element = element.parentElement) {
631 const color = getComputedStyle(element).backgroundColor;
632 if (isTransparent(color)) continue;
633 backdrops.push(color);
634 if (isOpaque(color)) break;
635 }
636​
637 visitElement(table, null);
638 try {
639 const images = await Promise.all(
640 contentOps.map((op) => (op.kind === "image" ? op.image : null)),
641 );
642​
643 // In device pixels: the canvas rounds its size, and a scaled fill could leave its last row half covered.
644 context.fillStyle = "#fff";
645 context.fillRect(0, 0, canvas.width, canvas.height);
646 for (const color of backdrops.toReversed()) {
647 context.fillStyle = color;
648 context.fillRect(0, 0, canvas.width, canvas.height);
649 }
650 context.scale(scale, scale);
651 paintOps(context, scale, blockOps, []);
652 paintOps(context, scale, contentOps, images);
653​
654 // A worker encode: Chromium runs main-thread encodes as idle tasks, ~1 s on a busy page.
655 const blob = await encodeCanvas(canvas, "srgb", 1, "image/png");
656 if (!blob) throw new Error("The table image could not be encoded.");
657 return blob;
658 } finally {
659 for (const url of objectUrls) URL.revokeObjectURL(url);
660 }