Playground · research instrument
Magnetic Field Simulator
Every field line here is marched through 3D space by a 4th-order Runge–Kutta integrator following the exact Biot–Savart field of real current loops and wires. Switch between a single loop, a Helmholtz pair, a magnetic bottle, a solenoid, an antiparallel wire pair, and a bar-magnet dipole and watch the geometry of the field reorganize — the uniform core of a Helmholtz coil, the pinched mirrors of a bottle, the confined interior of a solenoid, the circulating wrapping of parallel wires.
Independent research instrument — not claimed as MakerPortal shipped product code. Methods, equations, assumptions, and limitations are disclosed so you can inspect what the page does and does not establish.
Live field-line tracer
The canvas is a meridional cross-section through the symmetry axis of the current distribution: horizontal axis is (radial distance from the coil axis), vertical axis is (axial distance along the symmetry line). For coaxial configurations the magnetic field has zero out-of-plane -component in this plane, so every traced line stays exactly in-plane — no projection artifacts.
Configuration
Under cursor
— µT
—
⊙ current out of page · ⊗ into page
Meridional cross-section (x–z plane)
axis of symmetry vertical
Anatomy of the instrument
Every pixel above answers to the math below. Here is what each piece of the visualization and every control is actually doing, and why it is built that way.
The field-line canvas
- 01
The coordinate geometry. The canvas shows the – plane through the symmetry axis of the current distribution. (horizontal) is the radial distance from the axis; (vertical) is the axial coordinate. For coaxial loop configurations the field has zero -component by azimuthal symmetry, so field lines traced in this plane stay in this plane — no projection artifacts, no 3D ambiguity.
- 02
The vertical dashed axis. The dashed line at is the symmetry axis — it passes through the centers of all coaxial loops. On this axis the field is purely vertical. The heatmap and field-line color encodes on a logarithmic scale from the anchor blue (weak field) to the brand red (strong field). The color map is anchored at the 92nd-percentile field strength to avoid a single hotspot washing out the entire dynamic range.
- 03
The current glyphs. Each wire piercing the cross-section plane is marked by a circle: a filled dot ⊙ for current coming out of the page (toward you, +y), and a crossed circle ⊗ for current going into the page. The right-hand rule ties the glyph to the field circulation: with current out of the page at on the axis, the field lines wrap counterclockwise.
- 04
Flow-direction dashes. A dashed stroke overlay animates along the traced field lines to show direction. The dash offset advances by 0.6 px per frame at 60 fps, giving a gentle 6-second loop cycle. The animation is driven by
requestAnimationFrameonly when the flow toggle is on and the page is visible — idle when hidden or toggled off. The reduces-motion OS preference pauses the animation entirely. - 05
The heatmap. The magnitude is evaluated on a grid (down to 5 px cells, auto-coarsened to 8 or 12 if the initial pass exceeds 8 ms) using
compiledFieldAt— the same zero-allocation Struct-of-Arrays evaluator the field lines use. The heatmap is computed once per scene rebuild (not per frame) and cached to an offscreen canvas. Switching it off skips both evaluation and blit.
What every traced line satisfies — dr/ds = B̂(r)
A field line is a curve whose tangent vector at every point is parallel to . The RK4 integrator steps along the unit field direction at constant arclength , using 4 field evaluations per step. The arclength is fixed so lines in weak-field regions don't take huge leaps — field magnitude is encoded by line density and color, not step size.
Controls, readouts, and render loop
- 01
Preset buttons. Six configurations: single loop (a pure dipole), Helmholtz pair (two coplanar loops at spacing for uniform field), magnetic bottle (anti-Helmholtz: opposite currents create the mirror geometry), solenoid (3–12 turns creating a confined interior), two antiparallel wires (circulating field around each), and a dipole pair (coaxial loops at variable separation, approximating a bar magnet).
- 02
Current slider (10–400 A). Scales the field magnitude linearly. in DC magnetostatics — doubling the current doubles every field value everywhere. The loop radius is fixed at , so the on-axis dipole field at the loop center is .
- 03
Geometry slider. Separation between loops in units of the loop radius . At , two coaxial same-current loops form the Helmholtz condition — second derivative of vanishes on axis, producing the flattest possible central field. For the solenoid preset this slider controls the number of turns instead of separation.
- 04
Field-line count (6–24). Seeds are placed along the -axis at equally spaced radial distances from the loop center, half in each direction. Each seed is traced both forward and backward along , then joined into a single polyline. Lines with fewer than 4 points are discarded — these are seeds that land inside a loop or too close to a wire axis.
- 05
Cursor readout. Moving the mouse over the canvas evaluates
compiledFieldAtat the mapped physical coordinate and reports in (or above 1000 µT) and the field direction angle relative to the horizontal. This is the same solver used by the field lines and heatmap — a single source of truth. - 06
The render loop. There is no idle
requestAnimationFramespin. The scene rebuilds (segment compilation, field-line tracing, heatmap, cached layer draw) only on parameter change. The flow-direction dashes run an independent rAF loop that pauses when the canvas is offscreen (IntersectionObserver) or the page is hidden (visibilitychange). State changes issue a singledraw()call — no wasted frames while you read.
Gear behind this build
Magnetostatics hardware · 7 picks
Magnetic-field sensing7
$43.99SensorEC Buying GY-MPU9250 9 Axis Sensor 9 DOF Accelerometer with Gyroscope and Magnetic Field Sensors, 16 Bit AD Converter Data Output IIC I2C SPI
9-DoF IMU used in BLExAR's calibration builds. The onboard magnetometer is a 3-axis Hall-effect sensor — the same physics modeled by the magnetic field-line tracer — while the DMP outputs attitude as a quaternion matching CMHeadphoneMotionManager's format.
$11.99ToolGreen Magnetic Viewing Film 4x6 | Cool Magnets Science Kit | Magnetic Field Detector & Visual Aid for Physics Education | Ideal for Research & Magnetism Demonstrations
Shows Helmholtz pair uniformity and solenoid fringe fields in real life — directly comparable to the B_z magnitude readout under your cursor.
$18.01ToolMagnetic Field Viewing Film, Magnetic Field Viewer, 4 x 4 Inch
Green film renders flux lines from Biot-Savart superposition visible — lay it over a current loop and see the same dipole field this simulator traces via Runge-Kutta.
$18.99SensorGREDIA 3/4" Water Flow Sensor Food-Grade Switch Hall Effect Flowmeter Fluid Meter Counter 1-60L/min (Pack of 2)
Flow sensor used in BLExAR's water-metering build. Uses a Hall-effect magnetic sensor — the same Biot–Savart field the tracer models.
$49.18BookIntroduction to Electrodynamics
Chapter 5 derives Biot-Savart law and Helmholtz coil field — the exact integral this tracer evaluates with RK4 field-line marching.
$72.19SensorAEGTEST 8035 DC Gauss Meter, Telescopic Hall Sensor, Rechargeable Tesla Meter 0–2500 mT, Magnetometer with Data Logging and Alarm, Magnetic Field Strength Meter, ±5% General Accuracy for Daily Use
Measures B-field magnitude around loops/solenoids — hand-verify the Biot-Savart μ0/4π scaling this tracer computes before field-line integration.
$21.98ApparatusFerrofluid Magnetic Display – Science Education Magnetism Kit – Interactive Liquid Metal Physics Demonstration – Executive Desk Décor with Neodymium Magnets – STEM Learning Tool
Ferrofluid spikes under magnetic field emulate ferrofluid cooling in voice-coil gaps — the same thermal-magnetic mechanism reducing thermal compression via enhanced heat transfer.
Prices shown were retrieved from the Amazon Product Advertising API on 19 July 2026 and are indicative only — the price and availability on Amazon at the time of purchase apply.
More gear across every app: the full Gear list →
The math and physics, in full
From the Biot–Savart law through the finite-segment closed form to the RK4 integration — every equation this tracer evaluates, with the discretization choices and error bounds made explicit.
The Biot–Savart law, finite-segment form
In DC magnetostatics a steady current flowing through a wire produces a magnetic field at observation point . The differential form sums contributions from each infinitesimal length :
Differential Biot–Savart
Integrating around a closed loop gives the total field. For a straight wire segment from to the integral has a closed form. Let be the perpendicular distance from the wire line to , the unit vector along the wire (current direction), the unit vector from the wire line to , and the angles the wire endpoints subtend:
Finite-segment closed form
Implemented as segmentField() in src/lib/emfields.ts. The denominator is clamped at to avoid the wire-axis singularity. In the limit with this recovers the familiar infinite-wire result .
A circular loop is approximated by straight chords. The chord approximation error scales as for the field at distances comparable to the loop radius — 96 segments gives sub-pixel accuracy at the canvas scale. The total field at any point is the superposition (simple vector sum) of every segment's contribution.
Field-line integration: RK4
A magnetic field line satisfies the first-order ODE:
The field is renormalized at every step. A field line follows 's direction but not its magnitude — the magnitude encodes the local field strength, not the geometry of the line. Integrating the raw (unnormalized) would take giant steps in strong-field regions and tiny ones in weak regions, not a reflection of the actual curve geometry.
We integrate with classical 4th-order Runge–Kutta at fixed arclength step :
Classical RK4 weights
Global truncation error is . At 5 mm step size over a typical half-line of 500 steps (2.5 m physical arclength), the accumulated geometric error is under 0.1 mm — well below one canvas pixel (~0.9 mm physical). Each step evaluates compiledFieldAt 4 times (once per stage).
Each seed is traced in both forward () and reverse () directions. Traces stop when drops below (fade-out in weak field), after 1100 steps (divergence guard), or when the line leaves the bounding box — all well beyond the canvas viewport.
Key configurations: when the math locks in
Helmholtz condition: s = R
Two coaxial loops spaced by exactly their radius cancel both first and second axial derivatives at the midpoint. The central field is . The heatmap confirms this — the central region is uniformly tinted, no gradient visible.
On-axis loop field (verification formula)
This analytic formula is used as a unit-test oracle for fieldAt in emfields.ts. The chord-discretized field is verified to converge to this formula as .
Magnetic bottle: anti-Helmholtz
Opposite currents create a field that vanishes linearly at the midpoint and grows at both ends. The field-line geometry shows this as a pinch — lines converge at the strong-field ends and diverge in the weak center. Charged particles gyrate around the lines and reflect where the field strengthens (the magnetic mirror effect).
Long solenoid: ideal interior
For a solenoid with turns per meter and length , the interior field is nearly uniform and axial, with fringing at the ends. The tracer's solenoid preset stacks 3–12 loops along the axis — the interior field lines run parallel and evenly spaced, visually confirming the uniform-flux approximation.
Numerical method comparison
| Method | Order | Evaluations / step | Error / step |
|---|---|---|---|
| Euler (naive) | 1st | 1 | |
| Midpoint (RK2) | 2nd | 2 | |
| Classical RK4 (used here) | 4th | 4 | local, global |
RK4 over Euler is not a tweak — it's the difference between a closed-loop field line and one that spirals into the canvas border after 200 steps. The 4x field evaluation cost per step is paid once per scene rebuild, not per frame, so it never blocks user interaction.
Three real-world traps
Chord discretization error
A 96-chord polygon approximating a circle has a perimeter that's 99.97% of the exact circumference. But the field inside the loop — within a few chord-lengths of the wire — is more sensitive. At grid points very close to a chord, the finite-segment formula sees a straight wire, not a curved one. The error is at one chord-length from the loop and vanishes rapidly with distance. If you need interior-field precision for a real coil design, use a higher segment count or a true elliptic-integral formula — this tracer prioritizes visual fidelity over engineering-grade precision.
Wire-axis singularity
The Biot–Savart formula blows up as when (on the wire axis). The solver clamps the perpendicular distance at , returning for points closer than that. A real wire has finite radius — the field inside a cylindrical conductor grows linearly with from zero on the axis, not singular. This tracer treats wires as infinitely thin filaments, so the field near a glyph is capped, not physically accurate.
Seed placement bias
Field-line seeds are placed on the -axis only — no off-axis seeds, no adaptive density based on local . This means lines in regions far from the axis (e.g., the return field of a solenoid) are sparser than they should be for true flux-area encoding. A production field-line tracer would seed adaptively — more seeds where is high — but this adds complexity to collision detection (lines shouldn't cross) that we chose to defer.
The solver lives in src/lib/emfields.ts — unit-tested against the on-axis loop formula, the Helmholtz center value, and the circular field lines of a long straight wire.
The solver, in TypeScript
The finite-segment Biot–Savart evaluator and RK4 field-line tracer — the two functions that drive every pixel on this page. If you're porting this to C/C++ for an embedded magnetometer calibration tool, the logic ports directly.
Biot–Savart + RK4 tracer (TypeScript)
// Finite-segment Biot–Savart (src/lib/emfields.ts)
export function segmentField(seg: Segment, p: Vec3): Vec3 {
const eVec = sub(seg.b, seg.a);
const len = norm3(eVec);
if (len < 1e-15) return [0, 0, 0];
const e: Vec3 = scale(eVec, 1 / len);
const aToP = sub(p, seg.a);
const along = dot(aToP, e);
const perp = sub(aToP, scale(e, along));
let d = norm3(perp);
if (d < 1e-9) return [0, 0, 0]; // on wire axis
const nHat: Vec3 = scale(perp, 1 / d);
const bToP = sub(p, seg.b);
const ra = norm3(aToP);
const rb = norm3(bToP);
const cos1 = dot(aToP, e) / ra;
const cos2 = dot(bToP, e) / rb;
const mag = (MU0 * seg.current) / (4 * Math.PI * d) * (cos1 - cos2);
return scale(cross(e, nHat), mag);
}
// RK4 field-line tracer — dr/ds = B̂(r)
export function traceFieldLine(
cs: CompiledSegments, start: Vec3, opts: TraceOptions
): FieldLine {
const h = opts.reverse ? -opts.step : opts.step;
let p = start, k1 = null;
for (let i = 0; i < opts.maxSteps; i++) {
if (!k1) { const [d, ] = dir(p); if (!d) break; k1 = d; }
const [k2, ] = dir(add(p, scale(k1, h/2)));
if (!k2) break;
const [k3, ] = dir(add(p, scale(k2, h/2)));
if (!k3) break;
const [k4, ] = dir(add(p, scale(k3, h)));
if (!k4) break;
p = add(p, scale([
k1[0]+2*k2[0]+2*k3[0]+k4[0],
k1[1]+2*k2[1]+2*k3[1]+k4[1],
k1[2]+2*k2[2]+2*k3[2]+k4[2]
], h/6));
points.push(p);
const [nextK1, ] = dir(p);
k1 = nextK1;
if (Math.abs(p[0]) > bound || Math.abs(p[2]) > bound) break;
}
}Frequently asked questions
What is the Biot–Savart law?
It gives the magnetic field produced by a steady current: each infinitesimal length of current dl contributes a field dB proportional to I·dl × r̂ / r². Integrating over the whole circuit gives the total field at any point. Here every loop is broken into straight chords and each chord uses the exact finite-wire closed form, so the sum converges to the smooth loop as chord count grows.
Why use Runge–Kutta to draw field lines?
A field line is a curve everywhere tangent to B — mathematically, dr/ds = B̂(r). That is an ordinary differential equation. 4th-order RK4 integrates it with global truncation error O(h⁴), whereas naive Euler accumulates O(h) error per step and spirals field lines away from their true paths. The step size here is 5 mm per integration step, with up to 1100 steps per half-line, so the accumulated geometric error is well below one pixel.
What is a magnetic bottle?
Two coaxial coils carrying opposite currents (an anti-Helmholtz pair) create a field that is weak in the middle and strong at both ends. Charged particles spiralling along the lines get reflected at the high-field "mirrors" and bounce back and forth — the confinement principle behind magnetic-mirror fusion devices and the Van Allen radiation belts.
What does the Helmholtz spacing s = R do?
When two coaxial loops carrying the same current are spaced exactly one radius apart (s = R), the first and second spatial derivatives of B vanish at the midpoint. The result is a region of remarkably uniform magnetic field — the flattest possible for two coaxial coils. The on-axis midpoint field is B = (4/5)^(3/2) · μ₀ I / R.
What does this model leave out?
Pure DC magnetostatics: steady currents, filamentary (zero-thickness) wires, no magnetic materials (µ = µ₀ everywhere), no induced or eddy currents, no time variation. Loops are approximated by straight chords. It is exact for the idealised filamentary currents shown, but it is not a finite-element electromagnetic solver. Real-world effects like skin depth, wire thickness, and permeable cores are absent.
Shareable still
The instrument, captured—not illustrated.
This 16:9 frame is rendered from the real browser instrument above. It is the page's canonical preview for image search, link unfurls, and posts that need to show what the tool actually does.
Download 1280 × 720 JPEG