@manuel-rhdt/formel-wasm
v0.4.1
Published
Typeset MathML and LaTeX to SVG in the browser with an OpenType MATH font
Maintainers
Readme
@manuel-rhdt/formel-wasm
[!TIP] See below for how formel can be set up as a replacement for MathJax, instead of loading a npm package.
Typeset MathML and LaTeX to SVG in the browser with any OpenType MATH font, using formel.
The package uses math-core for LaTeX-to-MathML conversion and Formel for mathematical layout and rendering.
MathJax and KaTeX are self-contained JavaScript typesetters: they position glyphs from their own bundled fonts and leave the rest of the layout to the browser. Here the layout is computed in WebAssembly directly using a OpenType MATH font file, aiming to match what LuaTeX or XeTeX produce with that same font. The output is an SVG with fixed glyph positions.
Install
npm install @manuel-rhdt/formel-wasmQuick start
import init, { MathRenderer } from "@manuel-rhdt/formel-wasm";
import { inlineHtml } from "@manuel-rhdt/formel-wasm/dom";
await init();
const font = await fetch("/fonts/latinmodern-math.otf").then((r) => r.arrayBuffer());
const renderer = new MathRenderer(new Uint8Array(font));
// Inline math (scaled to 1em, aligned to the text baseline, colored with currentColor):
const eq = renderer.render_latex(String.raw`\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}`, false);
document.querySelector("#inline").innerHTML = inlineHtml(eq, { size: "1em" });
// Display math (centered block):
const block = renderer.render_latex(String.raw`\int_{-\infty}^{\infty} e^{-x^2}\,\mathrm{d}x = \sqrt{\pi}`, true);
document.querySelector("#block").innerHTML = inlineHtml(block, { display: true });All free OpenType MATH fonts work (New Computer Modern, Latin Modern, STIX Two, TeX Gyre, Asana, Fira Math, Noto Sans Math, …). Cambria Math works too, though its license does not allow web redistribution.
API
@manuel-rhdt/formel-wasm
await init(): initializes the WebAssembly module.new MathRenderer(fontBytes): loads an OpenType MATH font from aUint8Array.renderer.render_latex(latex, display): converts LaTeX (without$delimiters) and renders it, returning aRendering.renderer.render(mathml, debug): renders a MathML string, returning aRendering.renderer.render_latex_inline(latex, display)/renderer.render_inline(mathml): renders straight to HTML for a page: an<svg>sized in em of the surrounding text, on its baseline, incurrentColor, taking exactly the formula's room, withrole="math"and the spoken formula as its title.display(ordisplay="block"on<math>) marks itclass="formel-display"without placing it: give that class e.g.display: block; margin: 1em auto; max-width: 100%; height: autoin your stylesheet. Setfont-sizeon the<svg>to scale it. After it comes the MathML itself (with the LaTeX as anapplication/x-texannotation), in a<span class="formel-source" aria-hidden="true">hidden visually, as Wikipedia does, so search engines and scrapers still read the formula; both are wrapped in<span class="formel">. The MathML is copied in as it is, so pass trusted markup.renderer.render_svg(mathml): renders MathML to an SVG image fitted to the ink with a small margin, for a file or an<img>.renderer.set_font_features("'ss03'"): sets CSSfont-feature-settings(such as stylistic sets) for subsequent renders.renderer.add_font_face(fontBytes, unicodeRanges?, sizeAdjust?, fontFeatures?): uses another font for some characters, like a CSS@font-facewith aunicode-range.unicodeRangesis aUint32Arrayof pairs (the first and last codepoint of each range, e.g.[0x1D49C, 0x1D503]for the script letters),sizeAdjusta factor (0.9is 90%) andfontFeaturesafont-feature-settingsvalue. The font is used for a character in its ranges that it has a glyph for; otherwise the faces added before are tried, and last the font of the constructor, which gives the layout constants. Later calls take precedence over earlier ones. The font needs aMATHtable. See Mixed fonts.renderer.units_per_em(): returns the font's design units per em.
Rendering:{ svg, inline_svg, alt, width, height, baseline, box_x, box_y, box_width, box_height, units_per_em }, with lengths in font design units.inline_svgis the<svg>thatrender_inlinemakes, alone and placed inline.svgis the image, fitted to the formula's ink with a small margin, for files and<img>;width,heightandbaselinedescribe it, and thebox_*fields give the formula's own box within it.latex_to_mathml(latex, display): converts LaTeX to MathML via math-core without rendering.latex_error_range(latex, display): returns[start, end]in UTF-16 code units whenlatexhas a syntax error, orundefinedif valid.
@manuel-rhdt/formel-wasm/dom
inlineHtml(rendering, { size, display, color, alt }): the rendering'sinline_svg, at a size and colour.sizesets 1em of the formula ("1em","1.2em","18px", or a number in px) and becomes the element'sfont-size;display: truecenters it as a block instead of aligning to the text baseline;colordefaults to"currentColor".styleSvg(svg, { fg, bg, alt, mathml }): sets foreground/background colors, accessible title, and optional embedded MathML<metadata>.sizeSvg(svg, pxPerEm, unitsPerEm)/svgInPoints(svg, textSizePt, unitsPerEm): produces standalone SVGs with explicitpxorptdimensions.svgDataUri(svg)/svgDataUriEncoded(svg): encodes an SVG as a base64 or percent-encodeddata:image/svg+xmlURI.setPngResolution(pngBytes, dpi)/pixelsPerEm(textSizePt, dpi): writes a PNGpHYsDPI chunk for hi-DPI raster exports.
Bundlers and CDN
The package is built with wasm-bindgen --target web and resolves its .wasm binary via
import.meta.url, which Vite, webpack, Rollup, and esbuild handle out of the box. If you host the
files yourself, serve the .wasm file with Content-Type: application/wasm.
Without a bundler, load the ESM bundle from jsDelivr or unpkg:
import init, { MathRenderer } from "https://cdn.jsdelivr.net/npm/@manuel-rhdt/[email protected]/+esm";formel as a replacement for MathJax
If your MathJax page uses standard delimiters in ordinary page text and TeX commands that Formel
supports, replace the MathJax script tag with the automatic build. Replace VERSION with a published
package version that includes the browser builds.
<script src="https://cdn.jsdelivr.net/npm/@manuel-rhdt/formel-wasm@VERSION/formel-auto.min.js"></script>[!WARNING] On a first visit, Formel’s current WebAssembly bundle and math font typically require visitors to download more data than a standard MathJax setup.
[!NOTE] The larger download is the trade-off for supporting arbitrary OpenType MATH fonts.
Formel typesets the page on load and shares MathJax’s default TeX delimiters. Use \( … \) for
inline math and \[ … \] or $$ … $$ for display math. Add data-dollar="true" to also recognize
inline $ … $, or use data-root to limit scanning to a CSS selector.
Keep each formula and its delimiters in a single text node. The scan skips elements such as code,
pre, script, and style. In handwritten HTML, escape &, <, and > as &, <,
and >. Formulas that fail to render remain visible as source.
Pages that depend on MathJax configuration, extensions, or JavaScript APIs need migration. For
content added after startup, call formel.renderAll() after inserting it into the page.
Formulas show dimmed source while the renderer loads. Set data-placeholder="skeleton" to show a
placeholder instead, or data-css="false" to supply your own styles for .formel-pending.
Each formula carries an invisible text layer, so it can be selected, copied and found, and its text
stays in printed PDFs. Set data-text-layer="false" to leave it out, or call
renderer.set_text_layer(false) when using MathRenderer directly.
Each formula keeps its MathML, with the LaTeX as an annotation, hidden after its <svg>, and screen readers read that MathML. Set data-a11y="speech" to have them read the SVG's spoken title instead, or data-source="false" to leave the MathML out (the title is then read).
Choose a math font
If you omit data-font, Formel fetches the official STIX Two Math v2.13 font via jsDelivr.
Default font file
To choose another font, set data-font on the same script tag to a direct URL for an OpenType
MATH font (.otf or .ttf).
- For a font hosted on your site, use
data-font="/fonts/latinmodern-math.otf". Relative URLs resolve against the page’s base URL. - For a CDN-hosted font, use an absolute URL. The CDN must allow cross-origin fetches from your
page (for example, with
Access-Control-Allow-Origin: *). This example selects TeX Gyre Termes Math from jsDelivr.
<script src="https://cdn.jsdelivr.net/npm/@manuel-rhdt/formel-wasm@VERSION/formel-auto.min.js"
data-font="https://cdn.jsdelivr.net/gh/manuel-rhdt/formel@master/web/fonts/texgyretermes-math.otf"></script>Manual setup with a classic script
formel.min.js exposes the JavaScript API on window.formel and requires an explicit call to
formel.init(). The jsDelivr and unpkg package-root URLs serve this build. If you self-host it,
keep it next to formel_wasm_bg.wasm.
<script src="https://cdn.jsdelivr.net/npm/@manuel-rhdt/formel-wasm@VERSION/formel.min.js"></script>
<script>
formel.init().then(async (formel) => {
const font = await fetch("/fonts/latinmodern-math.otf").then((r) => r.arrayBuffer());
const renderer = new formel.MathRenderer(new Uint8Array(font));
document.querySelector("#eq").innerHTML =
formel.inlineHtml(renderer.render_latex("x^2", false), { size: "1em" });
});
</script>formel.init(url) takes an explicit module URL when the two files cannot sit side by side.
License
MIT for the engine (LICENSE). Third-party Rust crates compiled into the WebAssembly binary are listed in THIRD_PARTY.md. Fonts are not included and keep their own licenses.
