Feynman Diagram Generator in JavaScript – feynjs

Category: Chart & Graph , Javascript | November 30, 2026
Authorhepjs
Last UpdateNovember 30, 2026
LicenseMIT
Tags
Views0 views
Feynman Diagram Generator in JavaScript – feynjs

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+ &gt; Z &gt; 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 &gt; Z Z
Z &gt; e- e+
Z &gt; 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.

FunctionPurpose
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 optional line property 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);
FieldDescription
incoming, outgoingOptional arrays of leg IDs in top-to-bottom order.
verticesOptional array of objects: id (required), particle, coupling, shape, at: [x, y], and options (bracket-option string).
edgesRequired array of objects: from, to (required), particle, style, label, and options (bracket-option string).
switchesOptional 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

SyntaxPurpose
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, f2Conventional incoming and outgoing vertex names.
a b > c d, a b > g > c dCollision 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} > HIntermediate 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

OptionEffect
plain, fermion, anti fermion, majorana, anti majoranaSolid lines with different arrow directions.
photon, boson, charged boson, anti charged boson, gluonWavy boson or curly gluon lines.
scalar, dashed, charged scalar, anti charged scalar, ghost, dottedDashed or dotted propagators.
double, heavy, proton, ion, jet, ellipsisMultiple strokes, thick lines, beams, jet cones, or omitted legs.
susy, susy fermion, susy gluonSupersymmetric line styles.
hidden, invisibleOmit a line; invisible retains its layout constraint.
Particle nameSets 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.7Add markers or arrows at fractions of the line length.
out=-45, in=180, looseness=1.5Curve departure/arrival angles and curvature.
half left, half right, quarter left, quarter right, bend left, bend right, bend=30, bend left=40, bend right=40Preset or custom bends.
loop, min distance=2cmSelf-loop with a specified minimum size; combine with in/out angles.
length=1.5, length=2cmRelative or absolute line length.
no arrow, no label, overlay, heavy, dashed, dotted, double, jet, draw=noneModify 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, 3prongJet 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.

OptionEffect
Particle name, TeX label, or particle=Identifies an external leg.
dot, empty dot, square dot, crossed dot, slashed dotPoint markers.
blob, hatched blob, small blob, small hatched blobInteraction or decay discs.
jet, cone, insertion, circle=bJet endpoint, cone symbol, insertion mark, or labeled circle.
bag=proton, motion, moleculeValence-quark and flux-tube rendering, with optional motion or molecular grouping.
nucleus=208Pb, nucleus, A=16, Z=8, N=8Draw a nucleus by isotope or nucleon counts.
recoil, recoil=down, excited, pulse=high, emits=gammaNuclear recoil, excitation level, and radiation.
label=, label side=above/below/left/right, color=, rim=, size=Coupling label, placement, fill, rim, and dot size.
in, outExplicit incoming/outgoing role.
pulse, pulse=blueAnimated vertex or line emphasis.
eta=, phi=, deta=, dphi=Set or adjust leg direction in the kinematic view.

Diagram-Wide Directives

DirectiveEffect
in:, out:Explicit leg roles and order.
horizontal: a to b, horizontal': a to b, vertical: a to b, vertical': a to bRotate or mirror the figure relative to two points.
note: c "words", note: a--b "words" belowAdd annotations with pointers to vertices, edges, particles, or detector objects.
inline: aAlign 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 = textOverride 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: allLabel 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: manualChoose force, grid, or manually pinned layout.
grid: 45, grid: iso, grid forks: diagonalGrid directions or symmetric final-state forks.
final plane: onAlign final states on a vertical plane.
background: grid, debug: onDisplay a grid or diagnostic layout markings.
colour flow: on/only/off, charge colour: on, colours: bwColor-flow display, electric-charge colors, or monochrome output.
nucleon edges: ink/none/tintedOutline style for nucleons.
reveal: nFade the steps after n.
view: kinematic, projection: transverse/longitudinal, rotate: 30Schematic detector views and rotation (degrees).
reconstruct: off, show intermediate: trueDisplay final particles directly or include decaying particles in a kinematic view.
view: reaction, view: diagram, chain: straight/curve, modes: off, signal: onNuclear reaction/diagram displays, decay-chain shape and modes, detector signals.
view: lattice, lattice: 8x6, wilson loop:, plaquette:, link:, polyakov loop:, site:, boundary: periodic, axes: offDraw 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 fieldEffect
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, doubledBoolean flags for an overlaid straight stroke, thick stroke, outward Majorana arrows, or duplicate stroke.
color, clsStroke color and style class.
arrowsAtArray of { at, dir } entries; at is a fraction of line length and dir is 1 or -1.
jetCone, guide, impact, convertedBoolean flags for jet cone, invisible layout guide, impact parameters, or converted photon.
prongs1 or 3 tau-jet tracks.
objectDetector-object kind: jet, large, top, btag, ctag, tau, semivisible, emerging, displaced, leptonjet, met, disappearing, displacedlepton, heavycharged, track, or remnant.
adjectives, contentsModifier 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 defaultControls
unitX = 52
unitY = 34
Horizontal and vertical layout units.
fontSize = 17
fontFamily = "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 = 6
labelGap = 4
labelMargin = 3
Outer padding, line-to-label gap, and clearance around labels.
wordLabelScale = 0.78
couplingLabelScale = 0.82
crowdedLabelScale = 0.85
Relative sizing for word labels, coupling labels, and labels in crowded areas.
revealOpacity = 0.16Opacity of unrevealed parts (0 to 1).
hadronBraceDepth = 10
hadronBraceColor = "#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.3
size = 1
Finished drawing scale and optical sizing.
pulseColor = "#c0392b"
pulseSeconds = 2.4
noteColor = "#d0393f"
Animation color, duration in seconds, and annotation arrow color.

line settings

Setting and defaultControls
line.stroke = 1.5
line.heavy = 2
line.susy = 2.1
Normal, heavy, and SUSY stroke widths.
line.waveAmplitude = 4.2
line.waveLength = 13.5
Wave height and period.
line.coilRadius = 5.6
line.coilPitch = 10
line.coilAspect = 0.8
Gluon coil radius, period spacing, and lean ratio.
line.dash = 6
line.dashGap = 4
line.dotGap = 3.6
Dash length, gap between dashes, and dot spacing.
line.doubleSeparation = 3.2
line.tripleSeparation = 3.6
Separation between double and triple strokes.
line.arrowLength = 9.5
line.arrowWidth = 7.5
Arrowhead dimensions.
line.jetHalfAngle = 11
line.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.6
line.jetFade = 0.2
Cone opacity and fraction retained at the far end.
line.largeJetScale = 2.4
line.narrowJetScale = 0.8
line.trackWidth = 0.9
line.objectLegStretch = 1.6
Relative cone sizes, track stroke width, and detector-object leg length multiplier.

vertex settings

Setting and defaultControls
vertex.dot = 3.6
vertex.couplingDot = 4.6
vertex.crossedDot = 6.5
vertex.blob = 11
vertex.smallBlob = 4.6
vertex.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 = 7
vertex.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 defaultControls
colourFlow.gap = 3.4
colourFlow.width = 2.6
colourFlow.opacity = 0.6
colourFlow.arrowLength = 7
colourFlow.arrowWidth = 6.2
colourFlow.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 defaultControls
lifetime.width = 12
lifetime.opacity = 0.3
lifetime.color = "#3f90da"
lifetime.braceDepth = 6
Lifetime-band width, final opacity, color, and brace depth.

chargeColors settings

Setting and defaultControls
chargeColors.positive = "#e76300"
chargeColors.negative = "#3f90da"
chargeColors.either = "#832db6"
Colors for positive, negative, and plus-or-minus charge.

colors settings

Setting and defaultControls
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 defaultControls
forces.lineLength = 1
forces.legLength = 1
forces.length = 20
forces.legGive = 1
Natural propagator and external-leg lengths, length weight, and leg stiffness ratio.
forces.stageShrink = 0.7
forces.smallestLegStage = 0.7
Decay-stage length multiplier and lower limit for terminal leg size.
forces.evenAngles = 1
forces.passThroughEvenness = 0.3
forces.clearance = 20
forces.margin = 0.3
forces.vertexPad = 0.08
forces.minAngle = 25
Angle-evening weights, clearance force, minimum gap, dot radius allowance, and minimum angle (degrees).
forces.timeFlow = 2
forces.timeOrder = 50
forces.maxLean = 43
Forward direction weight, backward movement penalty, and maximum slope (degrees).
forces.uprightExchange = 0.6
forces.beamsScatter = 40
forces.scatterAngle = 10
Vertical exchange strength, scattering orientation strength, and minimum scattering angle (degrees).
forces.beams = 4
forces.beamsMirror = 30
forces.mirror = 2
forces.restLevel = 100
Incoming leg alignment, mirrored beams/branches, and level resonance weights.
forces.finalPlane = 2
forces.planeFirst = 0
forces.alignFinalStates = 1
forces.alignStretch = 1.6
forces.alignSteepest = 60
forces.alignLevel = 20
forces.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 = 20
forces.convergeLeeway = 4
forces.convergeReach = 1.8
Separation weight for outgoing legs, allowable convergence angle per generation, and near-leg distance.
forces.lightOutside = 200
forces.heavyCarriesOn = 20
forces.heavyTurn = 12
forces.wideLean = 60
forces.lightFermionLean = 45
Mass-dependent orientation weights and heavy-decay turning limits (degrees).
forces.offShellFlow = 0.4
forces.emittedFlow = 0.4
forces.heavyFlow = 22
forces.depthEase = 0.5
forces.settle = 0.8
Time-direction factors for off-shell, emitted and heavy particles, depth falloff exponent, and end-of-chain leveling fraction.
forces.givenOffFlow = 0
forces.givenOffLength = 0.75
forces.givenOffTurn = 40
forces.givenOffSide = 6
Accompanying fermion orientation weight, relative length, outward turning angle (degrees), and side weight.
forces.susyProductLength = 0.8
forces.susyProductHold = 4
forces.susyOpening = 50
SUSY decay product relative length, holding weight, and partner opening angle (degrees).
forces.equalProducts = 3
forces.deeperFlow = 8
forces.forwardFork = 25
forces.decayOpening = 40
Equal-length, deeper-branch direction, forward-fork weights, and minimum two-body opening (degrees).
forces.hadron = 20
forces.hadronSpacing = 0.6
forces.mesonGap = 0.25
forces.rail = 40
Hadron alignment weight, quark leg spacing, ellipse gap, and quark-rail alignment.
forces.blobBeamLength = 0.75
forces.blobBeamFlow = 0.2
Relative incoming beam length and time-direction factor at a blob.
forces.loop = 20
forces.loopLeg = 1
forces.loopUpright = 6
Loop-shape weight, relative corner-leg length, and upright orientation weight.
forces.pairTogether = 20
forces.pairOpening = 16
Particle-antiparticle pair alignment weight and opening angle (degrees).

SVG and CSS Hooks

Selector or attributePurpose
.feynman, .feynjs-rendered, data-processedSource container, rendered container, and processing marker.
svg.feynjsDiagram SVG.
.feynjs-susy, .feynjs-blob, .feynjs-collision, .feynjs-blob-labelSUSY line/label color, hadron fill, collision blob, and hadron label.
.feynjs-bg, .feynjs-brace, .feynjs-smallblobBackground-filled marks, hadron brace, and small decay vertices.
.feynjs-colour-flow, .feynjs-aheadColor-flow lines and unrevealed parts.
data-edge, data-from, data-to, data-particle, data-vertexIdentify line groups, their endpoints/particle, and vertex marks.
data-levelReveal step when levels are enabled.
metadata.feynjs-modelJSON 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-errorError 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

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.

You Might Be Interested In:


Leave a Reply