
feynjs is a JavaScript library that turns text into SVG Feynman diagrams for particle physics.
It accepts both TikZ-Feynman-style edge definitions and MadGraph-style process expressions, complete with automatic vertex placement and particle-specific line styles.
Features
- Force-directed, grid-based, and manually positioned diagram layouts.
- Scattering processes, decay chains, loops, and multi-panel figures.
- Built-in particle labels, propagator styles, hadrons, nuclei, and detector objects.
- Custom line styles, particle definitions, colors, and typography.
- Animated interaction markers, lifetime bands, and step-by-step reveals.
- Kinematic detector views and space-time lattice drawings.
- Diagram linting, layout scoring, and text descriptions for SVG accessibility.
- SVG, PNG, TIFF, and TikZ-Feynman export.
How To Use It
Basic Usage
Load the full browser build from a CDN, put your diagram expression inside an element with the feynman class and call feynjs.run() after the element exists.
<script src="https://cdn.jsdelivr.net/npm/feynjs/dist/feynjs-full.min.js"></script> <div class="feynman"> e- e+ > Z > e- e+ </div> <script>feynjs.run();</script>
Or install the npm package for module-based applications.
npm install feynjs
In a bundled JavaScript module, call render() to generate SVG markup for an HTML container.
<div id="diagram"></div>
import { render } from 'feynjs';
document.querySelector('#diagram').innerHTML = render(
'e- e+ > Z > e- e+'
);
Write Diagrams With Edge or Process Syntax
Use edge syntax to define connections, line styles, and labels. For example, draw electron-positron annihilation into a muon pair through a Z boson:
i1 [e-] -- a [dot] -- i2 [e+] a -- [Z, momentum=q] b [dot] f1 [mu-] -- b -- f2 [mu+]
For a decay chain, write the parent particles and their products using process syntax. Parentheses specify the decay of a particle at the point where it appears.
H > Z(> e- e+) Z(> mu- mu+)
To present two layouts side by side, place both sources in the same feynman element and separate them with a line of three hyphens.
--- Automatic
g g > {t} > H
--- Grid
layout: grid
g g > {t} > H
Build an Interactive Diagram Editor
Call render() whenever the reader submits new diagram text.
<textarea id="source" rows="4">H > Z Z
Z > e- e+
Z > mu- mu+</textarea>
<button id="draw" type="button">Draw diagram</button>
<p id="error" role="status"></p>
<div id="preview"></div>
<script>
const source = document.querySelector('#source');
const preview = document.querySelector('#preview');
const error = document.querySelector('#error');
function draw() {
try {
preview.innerHTML = feynjs.render(source.value, {
idPrefix: 'live',
theme: {
line: { stroke: 2 },
size: 0.85
}
});
error.textContent = '';
} catch (err) {
preview.replaceChildren();
error.textContent = err.message;
}
}
document.querySelector('#draw').addEventListener('click', draw);
draw();
</script>
Enable Downloads and Particle Tooltips
Pass options to run() when first rendering the diagram elements. The download control offers SVG, PNG, TIFF, and TikZ files. The particle tooltip shows details such as mass, charge, and spin.
<script>
feynjs.run({ download: true, tooltips: true });
</script>
JavaScript API
The full browser build exposes the API through the feynjs global. The smaller dist/feynjs.min.js build omits check(), describe(), measure(), and toSource(). The npm entry exposes the full API. Only the smaller browser build schedules automatic drawing on load; use run() or drawPageOnLoad() with the full build.
| Function | Purpose |
|---|---|
render(source, options?) | Returns SVG markup from text or a diagram object. |
run(options?) | Converts matching DOM elements into diagrams. Returns void. |
parse(source) | Parses text into a diagram with vertices, edges, hadrons, and directives before layout. |
check(source) | Returns structural findings with severity (error/warning), rule, message, and optional vertex. |
describe(source) | Returns process, incoming/outgoing particles, propagators, vertices, loops, pieces, and hadrons. |
explain(source) | Returns a human-readable description of the diagram. |
measure(source, theme?) | Returns a layout score: crossings, crowdedVertices, crowdedLabels, smallestAngle, stubs, aspect, and problems. |
toSource(diagram) | Serializes a diagram object to feynjs interchange text. |
toTikz(source, options?) | Returns TikZ-Feynman code with computed vertex positions. |
registerParticle(name, particle) | Registers a custom particle definition; returns void. |
registerLineStyle(name, style) | Registers a line style for use inside edge brackets; returns void. |
lookupParticle(name) | Returns the particle definition or undefined. |
particleNames() | Returns the registered particle names as an array. |
particleInfo(name) | Returns a readable particle-properties string or undefined. |
themeWith(overrides?) | Returns the default theme with overrides merged one level deep. |
startOnLoad(on) | Enables or disables automatic drawing on page load. Defaults to true; affects page-load drawing scheduled by drawPageOnLoad(). |
drawPageOnLoad() | Schedules page-load drawing and handles supported instant-navigation sites; useful with module imports. |
Other exported values:
defaultTheme: Default appearance and layout settings.lineStyles: Map of named line styles.particleProperties: Particle data, including optional charge, spin, color representation (colour), mass, valence quarks, and notes.INTERCHANGE_VERSION: Version of the interchange format (1).FeynError: Error class with an optionallineproperty for source errors.
Render Options
Options for render(source, options):
| Option (default) | Description |
|---|---|
theme (default theme) | Object with appearance and layout overrides. |
standalone (false) | Sets SVG colors explicitly for use outside the page. |
background (“#ffffff”) | Background for standalone exports. |
panelsPerRow (3) | Panel columns; joined panels default to one row. |
idPrefix (“feyn”) | Prefix for SVG IDs; use distinct prefixes for manually rendered diagrams. run() assigns its own unique prefixes. |
levels (false) | Adds data-level to parts for staged reveals. |
reveal (unset) | Number of steps to show normally; later steps appear faded. |
tooltips (false) | Adds plain-text particle tooltips to SVG. |
model (false) | Includes a JSON model in the SVG metadata. |
Run Options
run(options) accepts all render options, plus the following:
| Option (default) | Description |
|---|---|
querySelector (“.feynman:not([data-processed])”) | CSS selector for source containers. With the default selector, fenced Markdown blocks are also recognized. |
root (document) | DOM root to search within. |
download (false) | Adds an export menu to each diagram. |
progressive (false) | Renders visible diagrams first and schedules nearby diagrams as readers scroll. Automatic page-load rendering enables this option. |
tooltips (false) | Shows particle-property cards on hover. |
Draw Diagrams from JSON
For applications that store diagrams as structured data, pass an object with an edges array to the same drawing and analysis functions.
const diagram = {
incoming: ['i1', 'i2'],
outgoing: ['f1', 'f2'],
vertices: [
{ id: 'a', shape: 'dot' },
{ id: 'b', shape: 'dot' }
],
edges: [
{ from: 'i1', to: 'a', particle: 'e-' },
{ from: 'a', to: 'i2', particle: 'e-' },
{ from: 'a', to: 'b', particle: 'gamma' },
{ from: 'b', to: 'f1', particle: 'mu-' },
{ from: 'f2', to: 'b', particle: 'mu-' }
],
switches: { layout: 'grid' }
};
const svg = feynjs.render(diagram, { model: true });
const text = feynjs.toSource(diagram);
| Field | Description |
|---|---|
incoming, outgoing | Optional arrays of leg IDs in top-to-bottom order. |
vertices | Optional array of objects: id (required), particle, coupling, shape, at: [x, y], and options (bracket-option string). |
edges | Required array of objects: from, to (required), particle, style, label, and options (bracket-option string). |
switches | Optional object of diagram-wide directives and string values. |
Diagram Authoring Reference
Both syntaxes share the same styling and layout directives. You can call particleNames() to explore the registry in JavaScript.
Edges and Processes
| Syntax | Purpose |
|---|---|
a -- b -- c, a -- [style] b, a [options] | Connect vertices and set line or vertex properties. |
v at (x, y), v at (30:1) | Pin a point using Cartesian or polar coordinates in propagator-length units; explicit units such as cm also work. |
b [right=of a], [above left=1.5 of a], [above right=1 and 2 of a] | Relative placement from a positioned point. |
Newline, ;, , | End a statement. |
%, #, // | Start a line comment. |
i1, i2 / f1, f2 | Conventional incoming and outgoing vertex names. |
a b > c d, a b > g > c d | Collision with optional intermediate particle. |
t > b W+, W+(> e+ ve) | Subsequent decay or inline decay. Repeated decay statements apply in order; the last repeats. |
g g > {t} > H | Intermediate particle loop. |
ggF > H, VBF > H, VBS(W) > H > W+ W-, VBS(W, H) > W+ H W- | Gluon fusion, vector boson fusion, and vector boson scattering. |
2H 3H > 4He n, C(6p 8n), 12C* | Nuclear reaction, explicit nucleon composition, or excited nucleus. |
t~, ve, vm, vt, ta- | MadGraph particle names; tilde marks an antiparticle. |
Line Options
| Option | Effect |
|---|---|
plain, fermion, anti fermion, majorana, anti majorana | Solid lines with different arrow directions. |
photon, boson, charged boson, anti charged boson, gluon | Wavy boson or curly gluon lines. |
scalar, dashed, charged scalar, anti charged scalar, ghost, dotted | Dashed or dotted propagators. |
double, heavy, proton, ion, jet, ellipsis | Multiple strokes, thick lines, beams, jet cones, or omitted legs. |
susy, susy fermion, susy gluon | Supersymmetric line styles. |
hidden, invisible | Omit a line; invisible retains its layout constraint. |
| Particle name | Sets style, arrow, and label. |
label=, label'=, edge label=, edge label'=, label color= | Label, right-side label, and label color; quoted labels and their primed forms also work. |
momentum=, momentum'=, reversed momentum= (rmomentum), reversed momentum'= | Momentum arrows; prime changes the side and reversed changes direction. |
insertion=0.33, with arrow=0.3, with reversed arrow=0.7 | Add markers or arrows at fractions of the line length. |
out=-45, in=180, looseness=1.5 | Curve departure/arrival angles and curvature. |
half left, half right, quarter left, quarter right, bend left, bend right, bend=30, bend left=40, bend right=40 | Preset or custom bends. |
loop, min distance=2cm | Self-loop with a specified minimum size; combine with in/out angles. |
length=1.5, length=2cm | Relative or absolute line length. |
no arrow, no label, overlay, heavy, dashed, dotted, double, jet, draw=none | Modify or hide the chosen style; draw=none keeps the layout constraint. |
color=, pulse, radiation, lifetime={c\tau} | Line color, highlight, emitted radiation, and lifetime annotation. |
impact, converted, 3prong | Jet impact parameters, photon conversion, and three-prong tau jet. |
Detector-object names include lightjet, bjet, cjet, taujet, largejet, topjet, semivisiblejet, emergingjet, displacedjet, leptonjet, met, track, disappearingtrack, displacedlepton, hscp, and remnant. Prefix an object name with displaced to depict its flight before decay. Specify contents with expressions such as largejet(1b, W(2j)); contents can be jets (j, b), leptons (e, mu, l, tau), photons (g, y), quarks (q), and neutrinos (nu).
Vertex Options
Labels accept a subset of TeX, including Greek letters, superscripts, subscripts, accents, primes, \slashed{p}, \mathrm{}, and \text{}. Wrap labels containing commas in braces.
| Option | Effect |
|---|---|
Particle name, TeX label, or particle= | Identifies an external leg. |
dot, empty dot, square dot, crossed dot, slashed dot | Point markers. |
blob, hatched blob, small blob, small hatched blob | Interaction or decay discs. |
jet, cone, insertion, circle=b | Jet endpoint, cone symbol, insertion mark, or labeled circle. |
bag=proton, motion, molecule | Valence-quark and flux-tube rendering, with optional motion or molecular grouping. |
nucleus=208Pb, nucleus, A=16, Z=8, N=8 | Draw a nucleus by isotope or nucleon counts. |
recoil, recoil=down, excited, pulse=high, emits=gamma | Nuclear recoil, excitation level, and radiation. |
label=, label side=above/below/left/right, color=, rim=, size= | Coupling label, placement, fill, rim, and dot size. |
in, out | Explicit incoming/outgoing role. |
pulse, pulse=blue | Animated vertex or line emphasis. |
eta=, phi=, deta=, dphi= | Set or adjust leg direction in the kinematic view. |
Diagram-Wide Directives
| Directive | Effect |
|---|---|
in:, out: | Explicit leg roles and order. |
horizontal: a to b, horizontal': a to b, vertical: a to b, vertical': a to b | Rotate or mirror the figure relative to two points. |
note: c "words", note: a--b "words" below | Add annotations with pointers to vertices, edges, particles, or detector objects. |
inline: a | Align a point with the text’s math axis. |
every photon: color=blue, every dot: size=1.5, every edge:, every vertex: | Defaults for matching lines or vertices, overridden by local options. |
label: particle = text | Override a particle’s label throughout the diagram. |
meson:, baryon:, hadron: | Group legs; append [brace], [cap], or [hatched] for alternate shapes. |
edge labels: left, arrows: none, dots: all | Label side, arrow suppression, or vertex dots. |
scale: 1.5, size: small, title: | Zoom, optical size (tiny=0.55, small=0.72, normal/medium=1, large=1.3, or number), figure title. |
layout: default (v2), layout: grid, layout: manual | Choose force, grid, or manually pinned layout. |
grid: 45, grid: iso, grid forks: diagonal | Grid directions or symmetric final-state forks. |
final plane: on | Align final states on a vertical plane. |
background: grid, debug: on | Display a grid or diagnostic layout markings. |
colour flow: on/only/off, charge colour: on, colours: bw | Color-flow display, electric-charge colors, or monochrome output. |
nucleon edges: ink/none/tinted | Outline style for nucleons. |
reveal: n | Fade the steps after n. |
view: kinematic, projection: transverse/longitudinal, rotate: 30 | Schematic detector views and rotation (degrees). |
reconstruct: off, show intermediate: true | Display final particles directly or include decaying particles in a kinematic view. |
view: reaction, view: diagram, chain: straight/curve, modes: off, signal: on | Nuclear reaction/diagram displays, decay-chain shape and modes, detector signals. |
view: lattice, lattice: 8x6, wilson loop:, plaquette:, link:, polyakov loop:, site:, boundary: periodic, axes: off | Draw lattice sites, links, loops, and boundaries; items accept labels and colors. |
--- caption, ---[x], ---[otimes], ---[+], ---[=], ---[to], ---[cut] | Split or join panels. |
---[step: words], ---[step: words | one, two], ---[into: words] | Connect figures with a labeled step, input arrows, or branching bar. |
Custom Particles and Line Styles
Register a particle before rendering any source that references its name.
feynjs.registerParticle('ALP', {
style: feynjs.lineStyles.scalar,
label: 'a'
});
const svg = feynjs.render('e- e+ > ALP > mu- mu+');
A particle definition contains style (an EdgeStyle object), label (TeX-style text), and optional anti (boolean; reverses antiparticle fermion flow).
| EdgeStyle field | Effect |
|---|---|
line (required) | plain, wave, coil, dash, dot, double, triple, jet, ellipsis, or none. |
arrow (required) | 0 (none), 1 (forward), -1 (reverse), or 2 (two opposing arrows). |
overlay, heavy, arrowsApart, doubled | Boolean flags for an overlaid straight stroke, thick stroke, outward Majorana arrows, or duplicate stroke. |
color, cls | Stroke color and style class. |
arrowsAt | Array of { at, dir } entries; at is a fraction of line length and dir is 1 or -1. |
jetCone, guide, impact, converted | Boolean flags for jet cone, invisible layout guide, impact parameters, or converted photon. |
prongs | 1 or 3 tau-jet tracks. |
object | Detector-object kind: jet, large, top, btag, ctag, tau, semivisible, emerging, displaced, leptonjet, met, disappearing, displacedlepton, heavycharged, track, or remnant. |
adjectives, contents | Modifier strings and detector-object contents ({ kind, count, contents? }). |
Styling and Customization
Ordinary lines inherit the container’s CSS text color, which makes them adapt to light and dark page themes. Apply theme overrides to change the geometry of the diagram itself.
.feynman {
color: #27313a;
}
.dark .feynman {
color: #e9edf1;
}
svg.feynjs .feynjs-blob {
fill: rgba(120, 130, 140, 0.25);
}
feynjs.run({
theme: {
fontSize: 16,
line: { stroke: 1.8, waveAmplitude: 4 },
vertex: { dot: 4 },
engine: 'grid'
}
});
Theme Options
Pass these settings inside the theme object. Nested groups accept partial overrides, and unchanged fields retain their defaults. Dimensions are in pixels unless otherwise specified.
General settings
| Setting and default | Controls |
|---|---|
unitX = 52unitY = 34 | Horizontal and vertical layout units. |
fontSize = 17fontFamily = "math,'STIX Two Math','Cambria Math','New Computer Modern Math','Latin Modern Math',serif"captionFontFamily = "system-ui,-apple-system,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif" | Particle-label size and fonts for math labels and panel captions. |
padding = 6labelGap = 4labelMargin = 3 | Outer padding, line-to-label gap, and clearance around labels. |
wordLabelScale = 0.78couplingLabelScale = 0.82crowdedLabelScale = 0.85 | Relative sizing for word labels, coupling labels, and labels in crowded areas. |
revealOpacity = 0.16 | Opacity of unrevealed parts (0 to 1). |
hadronBraceDepth = 10hadronBraceColor = "#c0392b"hadronEllipseAspect = 0.45 | Hadron-brace depth and color; ellipse width relative to height. |
engine = "v2" | Layout engine: v2, grid, or manual. |
susyColor = "#c0392b"colourScheme = "default" | SUSY color; default or bw scheme. |
drawingScale = 1.3size = 1 | Finished drawing scale and optical sizing. |
pulseColor = "#c0392b"pulseSeconds = 2.4noteColor = "#d0393f" | Animation color, duration in seconds, and annotation arrow color. |
line settings
| Setting and default | Controls |
|---|---|
line.stroke = 1.5line.heavy = 2line.susy = 2.1 | Normal, heavy, and SUSY stroke widths. |
line.waveAmplitude = 4.2line.waveLength = 13.5 | Wave height and period. |
line.coilRadius = 5.6line.coilPitch = 10line.coilAspect = 0.8 | Gluon coil radius, period spacing, and lean ratio. |
line.dash = 6line.dashGap = 4line.dotGap = 3.6 | Dash length, gap between dashes, and dot spacing. |
line.doubleSeparation = 3.2line.tripleSeparation = 3.6 | Separation between double and triple strokes. |
line.arrowLength = 9.5line.arrowWidth = 7.5 | Arrowhead dimensions. |
line.jetHalfAngle = 11line.jetMaxHalfWidth = 13 | Jet cone half-angle (degrees) and maximum half-width. |
line.jetColor = "#3f90da"line.bJetColor = "#3f90da"line.cJetColor = "#23a46d"line.lightJetColor = "#e07b39"line.tauJetColor = "#a472ca"line.largeJetColor = "#8a919c" | Colors of ordinary, b, c, light, tau, and large jets. |
line.jetShade = 0.6line.jetFade = 0.2 | Cone opacity and fraction retained at the far end. |
line.largeJetScale = 2.4line.narrowJetScale = 0.8line.trackWidth = 0.9line.objectLegStretch = 1.6 | Relative cone sizes, track stroke width, and detector-object leg length multiplier. |
vertex settings
| Setting and default | Controls |
|---|---|
vertex.dot = 3.6vertex.couplingDot = 4.6vertex.crossedDot = 6.5vertex.blob = 11vertex.smallBlob = 4.6vertex.insertion = 4.5 | Radii for markers, coupling dots, crossed dots, blobs, and insertion cross half-size. |
vertex.blobFill = "rgba(100, 120, 150, 0.2)"vertex.smallBlobFill = "#9aa1ab"vertex.hatchSpacing = 2.8 | Blob and decay-marker fill; hatch spacing. |
vertex.nucleusUnit = 7vertex.proton = "#b8493b"vertex.neutron = "#5d6b85" | Nucleon size and particle colors. |
vertex.nucleonEdge = "#2b2b2b"vertex.protonEdge = "#4f1f19"vertex.neutronEdge = "#252c3a" | Nucleon outline colors (none suppresses an outline). |
colourFlow settings
| Setting and default | Controls |
|---|---|
colourFlow.gap = 3.4colourFlow.width = 2.6colourFlow.opacity = 0.6colourFlow.arrowLength = 7colourFlow.arrowWidth = 6.2colourFlow.turn = 14 | Offset, stroke width, opacity, arrow dimensions, and turning distance from the vertex. |
colourFlow.palette = ["#e0241b", "#1f9e4a", "#2f6fdf"]colourFlow.anti = ["#00a7c4", "#c8379f", "#f0b000"] | Three color and three anticolor values. |
lifetime settings
| Setting and default | Controls |
|---|---|
lifetime.width = 12lifetime.opacity = 0.3lifetime.color = "#3f90da"lifetime.braceDepth = 6 | Lifetime-band width, final opacity, color, and brace depth. |
chargeColors settings
| Setting and default | Controls |
|---|---|
chargeColors.positive = "#e76300"chargeColors.negative = "#3f90da"chargeColors.either = "#832db6" | Colors for positive, negative, and plus-or-minus charge. |
colors settings
| Setting and default | Controls |
|---|---|
colors.blue = "#3f90da"colors.orange = "#e76300"colors.red = "#e0241b"colors.gray = "#94a4a2"colors.grey = "#94a4a2"colors.purple = "#832db6"colors.brown = "#a96b59"colors.yellow = "#ffa90e"colors.tan = "#b9ac70"colors.ash = "#717581"colors.cyan = "#92dadd"colors.green = "#2e8b57"colors.pink = "#d6468f"colors.teal = "#1a9a9d"colors.gold = "#c99700"colors.black = "#000000" | Named CSS colors available in diagram source. |
forces settings
| Setting and default | Controls |
|---|---|
forces.lineLength = 1forces.legLength = 1forces.length = 20forces.legGive = 1 | Natural propagator and external-leg lengths, length weight, and leg stiffness ratio. |
forces.stageShrink = 0.7forces.smallestLegStage = 0.7 | Decay-stage length multiplier and lower limit for terminal leg size. |
forces.evenAngles = 1forces.passThroughEvenness = 0.3forces.clearance = 20forces.margin = 0.3forces.vertexPad = 0.08forces.minAngle = 25 | Angle-evening weights, clearance force, minimum gap, dot radius allowance, and minimum angle (degrees). |
forces.timeFlow = 2forces.timeOrder = 50forces.maxLean = 43 | Forward direction weight, backward movement penalty, and maximum slope (degrees). |
forces.uprightExchange = 0.6forces.beamsScatter = 40forces.scatterAngle = 10 | Vertical exchange strength, scattering orientation strength, and minimum scattering angle (degrees). |
forces.beams = 4forces.beamsMirror = 30forces.mirror = 2forces.restLevel = 100 | Incoming leg alignment, mirrored beams/branches, and level resonance weights. |
forces.finalPlane = 2forces.planeFirst = 0forces.alignFinalStates = 1forces.alignStretch = 1.6forces.alignSteepest = 60forces.alignLevel = 20forces.alignGap = 0.35 | Final-state alignment weights, plane-first switch (0/1), outgoing-leg alignment (0/1), stretch limit, angular limits (degrees), and gap. |
forces.noConverging = 20forces.convergeLeeway = 4forces.convergeReach = 1.8 | Separation weight for outgoing legs, allowable convergence angle per generation, and near-leg distance. |
forces.lightOutside = 200forces.heavyCarriesOn = 20forces.heavyTurn = 12forces.wideLean = 60forces.lightFermionLean = 45 | Mass-dependent orientation weights and heavy-decay turning limits (degrees). |
forces.offShellFlow = 0.4forces.emittedFlow = 0.4forces.heavyFlow = 22forces.depthEase = 0.5forces.settle = 0.8 | Time-direction factors for off-shell, emitted and heavy particles, depth falloff exponent, and end-of-chain leveling fraction. |
forces.givenOffFlow = 0forces.givenOffLength = 0.75forces.givenOffTurn = 40forces.givenOffSide = 6 | Accompanying fermion orientation weight, relative length, outward turning angle (degrees), and side weight. |
forces.susyProductLength = 0.8forces.susyProductHold = 4forces.susyOpening = 50 | SUSY decay product relative length, holding weight, and partner opening angle (degrees). |
forces.equalProducts = 3forces.deeperFlow = 8forces.forwardFork = 25forces.decayOpening = 40 | Equal-length, deeper-branch direction, forward-fork weights, and minimum two-body opening (degrees). |
forces.hadron = 20forces.hadronSpacing = 0.6forces.mesonGap = 0.25forces.rail = 40 | Hadron alignment weight, quark leg spacing, ellipse gap, and quark-rail alignment. |
forces.blobBeamLength = 0.75forces.blobBeamFlow = 0.2 | Relative incoming beam length and time-direction factor at a blob. |
forces.loop = 20forces.loopLeg = 1forces.loopUpright = 6 | Loop-shape weight, relative corner-leg length, and upright orientation weight. |
forces.pairTogether = 20forces.pairOpening = 16 | Particle-antiparticle pair alignment weight and opening angle (degrees). |
SVG and CSS Hooks
| Selector or attribute | Purpose |
|---|---|
.feynman, .feynjs-rendered, data-processed | Source container, rendered container, and processing marker. |
svg.feynjs | Diagram SVG. |
.feynjs-susy, .feynjs-blob, .feynjs-collision, .feynjs-blob-label | SUSY line/label color, hadron fill, collision blob, and hadron label. |
.feynjs-bg, .feynjs-brace, .feynjs-smallblob | Background-filled marks, hadron brace, and small decay vertices. |
.feynjs-colour-flow, .feynjs-ahead | Color-flow lines and unrevealed parts. |
data-edge, data-from, data-to, data-particle, data-vertex | Identify line groups, their endpoints/particle, and vertex marks. |
data-level | Reveal step when levels are enabled. |
metadata.feynjs-model | JSON geometry and model when model output is enabled: feynjs (format version), unit (x/y scale), vertices (id, x/y, at, optional role/label/particle/shape), and edges (id, from, to, line, optional particle/label). |
pre.feynjs-error | Error text and original source if automatic rendering fails. |
Tooltip CSS Custom Properties
| Property (default) | Purpose |
|---|---|
--feynjs-tooltip-bg (rgba(255, 255, 255, .38)) | Card background. |
--feynjs-tooltip-fg (#1b1f24) | Text color. |
--feynjs-tooltip-accent (#c0392b) | Accent color. |
--feynjs-tooltip-border (rgba(255, 255, 255, .75)) | Border color. |
--feynjs-tooltip-font (system-ui, -apple-system, "Segoe UI", sans-serif) | Card font family. |
Export SVG or TikZ-Feynman
For an SVG file that you plan to open outside a themed web page, use standalone: true. Pass the same diagram source to toTikz() when you need a LaTeX figure.
const source = 'g g > {t} > H';
const svg = feynjs.render(source, {
standalone: true,
background: '#ffffff'
});
const tex = feynjs.toTikz(source, {
standalone: false,
unit: 1.6
});
| Option (default) | Description |
|---|---|
standalone (true) | Produces a complete LaTeX document. Set false for the picture code alone. |
unit (1.6) | Propagator length in centimeters. |
theme (default theme) | Layout and appearance overrides. |
Import TikZ-Feynman figures through the conversion module. It handles \feynmandiagram, \vertex, and \diagram statements and returns one feynjs source string per figure. Figures that use general TikZ drawing commands such as \node or \draw need to be converted to supported statements first.
import { fromTikz } from 'feynjs/tikz';
const figures = fromTikz(String.raw`\feynmandiagram {
i1 -- [fermion] a -- [fermion] i2,
a -- [photon] b,
f1 -- [fermion] b -- [fermion] f2,
};`);
For script-tag integration, load the conversion module before calling feynjsTikz.fromTikz(tex).
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/feynjs-tikz.min.js"></script>
Markdown Integration
Use a fenced feynman or feynjs block in Markdown. The standard browser build recognizes the corresponding language classes and draws them on page load. In MkDocs, add a custom fence to preserve the source and load the script with your existing settings:
extra_javascript: - https://cdn.jsdelivr.net/npm/[email protected]/dist/feynjs.min.js markdown_extensions: - pymdownx.superfences: custom_fences: - name: feynman class: feynman format: !!python/name:pymdownx.superfences.fence_div_format
Write the diagram in a fenced block with the language set to feynman.
```feynman
g g > {t} > H
```Related Resources
- Render LaTeX TikZ Code as SVG Directly in Browser – TikZJax
- Pele: Render Mermaid Diagrams to SVG with JavaScript
- jQuery.Feyn: Drawing Feynman Diagrams with SVG
FAQs
Q: Do I need LaTeX or MathJax to draw Feynman diagrams in the browser?
A: No. feynjs draws SVG directly with JavaScript and uses the browser’s available math fonts for labels.
Q: How do I render diagrams added to a page dynamically?
A: Call feynjs.run() after inserting new source elements. Existing processed elements are skipped. For updating an existing diagram, retain the original text in your application and call render() again.
Q: Can feynjs validate whether a particle interaction is physically possible?
A: The check() function flags structural problems such as disconnected vertices, unpaired fermion lines, and incorrect arrow flow. Physical validity and conservation laws require a physics model.
Q: Can I generate Feynman diagrams during a static site build?
A: Yes. Import render() from the npm package in Node.js and write the returned SVG markup to a file or include it in generated HTML.







