Topic

Exporting: images, PDF, LaTeX and text

Any scene that can be drawn on a canvas can also leave the browser: as an SVG or PNG image, as a PDF, as TikZ or PGFPlots for a LaTeX paper or worksheet, and as plain text for a terminal, a README or an email. All of them take the same layers and options as drawScene, and none needs anything installed.

const layers = [{ item: graph("x^3/4 - x", {}, vp).exact(), color: "#0f766e" }, label([2, 2], "y = \\tfrac{x^3}{4} - x")];
sceneSVG(vp, layers, { axes: true });                  // an <svg> string
await scenePNG(vp, layers, { axes: true, scale: 2 });  // PNG bytes, at twice the size
scenePDF(vp, layers, { axes: true });                  // PDF bytes, vector
sceneTikZ(vp, layers, { axes: true, width: 8 });       // a tikzpicture, 8 cm wide
scenePGFPlots(vp, layers, { axes: true, width: 8 });   // a PGFPlots axis
sceneASCII(vp, layers, { axes: true, cols: 72 });      // 72 columns of text

Which one to use

FormatGood forLabels
SVGWeb pages, slides, image editors, printing from a browserKaTeX HTML (with tex) or plain text
PNGAnywhere an image goes: messages, documents, slides, social posts, app share sheetsPlain text
PDFPrinting, handouts, attaching a sharp figure without LaTeXPlain text (Helvetica and Symbol)
TikZLaTeX documents: papers, exams, worksheets, Beamer slides. The figure uses the document's own fonts and can be edited by hand afterwards.Real TeX, typeset by LaTeX
PGFPlotsLaTeX documents whose other plots use PGFPlots: axes, ticks and grid in its house style, curves as \addplot you can restyle or add a legend toReal TeX
TextTerminals and REPLs, code comments, plain-text email, quick checks in tests, screen readers that read textPlain text (x² ≤ 1/2, or x^2 <= 1/2 in ASCII)

TikZ

sceneTikZ(vp, layers, options) returns a tikzpicture. Unlike the SVG, which is in pixels, its coordinates are the viewport's world coordinates: the picture sets TikZ's x and y units so the viewport is width centimetres wide, and a corner at (4,0)(4, 0) is written (4,0). That makes the file readable and easy to adjust: move a label, add an arrow, change a color.

  • Exact pieces stay exact. Polygon corners, segment ends and tick marks are written at their values (rounded to a tenth of a pixel, so 83\tfrac{8}{3} shows as 2.667). Circles are written as TikZ ellipses with their true center and radius, not as many-sided polygons. Labels keep their LaTeX, so a point labelled with toTeX() shows (2+255,1+55)\left(2 + \tfrac{2\sqrt5}{5}, 1 + \tfrac{\sqrt5}{5}\right) set by LaTeX itself.
  • Certified frames stay certified. Shaded cells from exact() become filled rectangles (side-by-side cells are merged), so the printed picture still provably contains the graph. Quick sketches become paths, with points that lie within a quarter pixel of a straight line dropped (simplify, in pixels; 0 keeps every point).
  • Sizes. width and height are in centimetres (height defaults to the viewport's aspect ratio). Line widths, dashes and dot radii are given by the scene in pixels and written as pt times pt (default 0.5), so a 2-pixel curve is a 1 pt line whatever the figure's size.
  • Colors become \definecolor lines at the top of the picture (rm1, rm2, …); xcolor names such as red or blue!50 pass through.
  • A complete file. standalone: true wraps the picture in a standalone document that compiles with pdflatex as it is, giving a tightly cropped PDF. preamble adds lines to it. In your own document, load tikz (and amsmath if labels use it) and paste the picture.
  • axes: true draws the grid, axes and tick labels at exact tick values. background fills the viewport; clip: false lets drawing run past its edges.
import { writeFileSync } from "node:fs";
writeFileSync("figure.tex", sceneTikZ(vp, layers, { axes: true, standalone: true }));
// $ pdflatex figure.tex   -> figure.pdf

The lower-level tikzElements(vp, prims, options) turns any list of primitives (from primitives, or your own) into TikZ commands without the surrounding picture.

PGFPlots

scenePGFPlots(vp, layers, options) puts the layers in a PGFPlots axis sized width × height cm with the viewport as its limits. PGFPlots draws the axes, ticks and grid itself (axes: true; otherwise the axis is hidden) and clips to the viewport. Curves become \addplot coordinates, so you can restyle them or add \legend; regions, certified cells, circles, points and labels are TikZ paths in axis coordinates, exactly as in the TikZ export. axisOptions adds keys to the axis (for example "xlabel=$x$, ylabel=$y$"). The document needs \usepackage{pgfplots} and \pgfplotsset{compat=1.11} or later; standalone: true includes both.

PNG

await scenePNG(vp, layers, options) gives the bytes of a PNG file. scale multiplies the pixel size (2 for sharp images on high-density screens), and background fills it (it is transparent otherwise).

  • In a browser the scene is painted with drawScene on an OffscreenCanvas, so the PNG matches what is on screen.
  • In Node, Bun or a worker without a canvas, a built-in renderer paints the same primitives with anti-aliased edges, and labels in a small built-in font (DejaVu Sans). Certified cells land exactly on their pixels. engine: "software" chooses it in a browser too; rasterize and encodePNG are its two halves.

PDF

scenePDF(vp, layers, options) gives the bytes of a one-page vector PDF the size of the viewport (pt points per pixel, default 0.75, so 96 pixels make an inch). Lines, regions and certified cells stay vector and print sharply at any size; circles are true curves. Labels use the PDF base fonts, Helvetica with Symbol for ≤\le, π\pi,  \sqrt{\ } and Greek, so they are plain text, not typeset TeX. For TeX labels, export TikZ with standalone: true and run pdflatex.

import { writeFileSync } from "node:fs";
writeFileSync("figure.png", await scenePNG(vp, layers, { axes: true, scale: 2, background: "#fff" }));
writeFileSync("figure.pdf", scenePDF(vp, layers, { axes: true }));

// In a browser: offer a download.
const url = URL.createObjectURL(new Blob([scenePDF(vp, layers)], { type: "application/pdf" }));

Text

sceneASCII(vp, layers, options) draws the scene with characters, cols wide (default 72) and rows tall (default: the viewport's shape, counting a character as twice as tall as it is wide). Three character sets:

modeCharactersDetail per character
"ascii" (default)- | / \ _ for curves, chosen by the curve's direction; # for solid blocks; . for shaded regions; @ and O for filled and open dots; - | + for axes1, with direction
"braille"Unicode Braille patterns ⡇⠑⢄⣀, ░ shading, ●○ dots, box-drawing axes2 × 4 dots
"blocks"Unicode quadrant blocks ▖▗▘▝▀▄▌▐█2 × 2 blocks

ASCII is safe everywhere, including old terminals and source files. Braille gives the smoothest curves but needs a font that has the patterns (most monospace fonts do). Labels are written last, so they stay readable; in ASCII mode they are spelled with 7-bit characters (asciiText: x² becomes x^2, ≤ becomes <=). Tick labels give way to the picture when there is no room for them.

Certified frames stay certified here too. A character is inked when any ink touches it, so every character the certified cells pass through is marked: the picture is coarser, never wrong. To get exactly one character per certified pixel, make the viewport cols by rows pixels.

Other options: border: true frames the picture, color: true adds 24-bit ANSI colors for terminals, labels: false leaves labels out. asciiElements(vp, prims, options) works on primitives directly.

// In a terminal (Node or Bun):
console.log(sceneASCII(vp, [graph("sin(x)", {}, vp).exact()], { axes: true, mode: "braille", color: true }));

The box below draws one scene several ways. Change mode, cols or the layers, and press Run.

Try itEdit the code and run it with @ratmath/graphics and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math, and SHOW(svg) draws a picture.
Ctrl/⌘ + Enter runs