Magnetic Field Line Simulator
Drop bar magnets and current-carrying wires on a canvas and watch the real magnetic field appear: RK4-traced field lines, a log-scaled arrow grid, a |B| heatmap, and animated iron filings with the ferrofluid spike look.
Preset arrangements
Render layers
Click adds
Tap a magnet or wire on the canvas to select it — then rotate it, flip its polarity, change its strength, or delete it.
What field lines actually represent
The most important thing to understand about magnetic field lines is that they do not exist. There is no thread of anything stretched between the poles of a magnet. The magnetic field B is a vector defined at every single point in space — a continuum, not a set of curves. A field line is a bookkeeping device invented by Michael Faraday: a curve drawn so that its tangent at every point is parallel to B there. This simulator constructs them literally that way, by integrating dr/ds = B̂ with a fourth-order Runge–Kutta step from seed points ringed evenly around each source.
What the picture does encode honestly is strength. By the standard convention, the density of lines is proportional to |B| — lines crowd together where the field is intense and spread apart where it is weak. That is why the region between an attracting N–S pair looks packed, and why the field far from a magnet fades to almost nothing. Where the picture is misleading is in suggesting discreteness: the true number of lines is infinite, and the simulator's density slider changes only how many you choose to draw.
Two hard rules follow from the physics. Field lines never cross. If they did, the field would have two different directions at one point, which is meaningless for a vector-valued function. (Lines can meet at a null point, where B = 0 exactly and no direction is defined — you can find one on the canvas between two identical repelling N poles.) And magnetic field lines always close on themselves. They have no starting point and no ending point. Electric field lines begin on positive charges and end on negative ones, because isolated electric charges exist. Their magnetic counterparts — magnetic monopoles — have never been observed, despite searches spanning more than a century.
That absence is Maxwell's second equation: ∇ · B = 0. Read as a statement about geometry, it says that the net magnetic flux through any closed surface is exactly zero — every line that enters must also leave. A bar magnet's lines emerge from the N pole, arc through space, enter the S pole, and continue through the interior of the magnet back to N, completing the loop. Break the magnet in half hoping to isolate a pole and you get two smaller magnets, each with its own N and S. You cannot get a monopole by cutting, because the magnetism comes from circulating currents and electron spin, and a current loop is intrinsically dipolar.
Dipole 1/r³ versus wire 1/r: why the falloff matters
The two source types in this simulator obey genuinely different distance laws, and the difference is dramatic. For a point magnetic dipole with moment m, the field at displacement r is
B(r) = (μ₀ / 4π) · [ 3 r̂ (m · r̂) − m ] / |r|³
Every component carries a 1/r³. The angular factor in brackets is what produces the familiar lobed shape: on the dipole axis the field points along m and has magnitude 2μ₀m/4πr³; in the equatorial plane it points antiparallel to m and is exactly half as strong. That factor-of-two axis/equator ratio is a good sanity check — hover the pointer along a magnet's axis, then the same distance out to its side, and compare the |B| readout.
An infinite straight wire carrying current I perpendicular to the screen is a completely different geometry. Ampère's law applied to a circular loop of radius r around the wire gives B · 2πr = μ₀I, so
B = μ₀I / (2πr), direction = ẑ × r̂ (purely tangential)
The field has no radial component at all — it circles the wire in perfect concentric rings. Because the wire is infinite it never "runs out" of source, so the decay is only 1/r. Here is how the two compare, normalized to 1 at r = 1:
| Distance r | Wire (1/r) | Dipole (1/r³) | Dipole ÷ wire |
|---|---|---|---|
| 1× | 1.000 | 1.000 | 1.00 |
| 2× | 0.500 | 0.125 | 0.25 |
| 5× | 0.200 | 0.008 | 0.04 |
| 10× | 0.100 | 0.001 | 0.01 |
| 100× | 0.010 | 10⁻⁶ | 10⁻⁴ |
Ten times farther away, the wire has lost 90% of its field and the dipole has lost 99.9%. This is exactly why the heatmap and arrow grid in the simulator use logarithmic scaling: across a 760-pixel canvas a dipole field spans five or more orders of magnitude, and any linear color or length mapping would show a blinding white dot at each pole and pure black everywhere else. Taking log₁₀|B| compresses those decades into a range the eye can actually read.
The same falloff explains a lot of real engineering. A fridge magnet is imperceptible at arm's length; Earth's dipole field (≈50 μT at the surface, so weak that a compass needle is a sensitive instrument) still dominates near-Earth space simply because the planet's moment is about 7.7 × 10²² A·m². And it is why MRI machines need superconducting solenoids rather than permanent magnets to hold 1.5–3 T over a whole human torso.
The right-hand rule for a current-carrying wire
Ampère's law fixes the magnitude of a wire's field, but the sign convention — which way the field circulates — is set by the right-hand rule. Point the thumb of your right hand along the direction of conventional current (positive charge flow, which is opposite to the actual electron drift). Your curled fingers then trace the direction of B.
- Current out of the screen (⊙): drawn as a dot — the tip of an arrow flying toward you. The field circulates counter-clockwise. In vector form,
B ∝ ẑ × r̂, and withr̂ = (x, y)/rthat evaluates to(−y, x)/r— precisely what the simulator computes. - Current into the screen (⊗): drawn as crossed fletchings — the tail feathers of an arrow flying away. The circulation reverses to clockwise. Flipping the sign of I flips B everywhere.
- Two parallel wires, same direction: their fields partially cancel in the gap between them and reinforce outside, and the wires attract. This force is what historically defined the ampere: two infinite parallel wires one metre apart carrying 1 A each attract with 2 × 10⁻⁷ N per metre. (Since the 2019 SI redefinition the ampere is fixed instead by the elementary charge, but the physics is unchanged.)
- Two anti-parallel wires (⊙ and ⊗): fields add in the gap, and the wires repel. Load the "Anti-parallel wires" preset and watch the iron filings pack densely into the centre channel.
The second right-hand rule. Curl your fingers along the direction of current flowing around a loop, and your extended thumb points along the loop's magnetic moment m — its north pole. This is the bridge between the two source types here: the "Helmholtz pair" preset is four wires, but because the two on each side carry opposite currents they act as a pair of coil cross-sections, and far away the whole arrangement looks like a single dipole. Every bar magnet is, at bottom, an enormous number of atomic current loops pointing the same way.
Note the Helmholtz geometry specifically: two coaxial coils separated by a distance equal to their radius. At that exact spacing the second derivative of the on-axis field vanishes along with the first, producing a remarkably uniform field through the central region — the standard laboratory recipe for a controlled, homogeneous B.
How real ferrofluid spikes form: the Rosensweig instability
The spike rendering in this simulator is a stylization of a real, well-characterized phenomenon. Ferrofluid is a colloid: roughly 10 nm magnetite (Fe₃O₄) particles, each coated with a surfactant that keeps them from clumping, suspended in oil or water. The particles are small enough that thermal motion keeps them dispersed and randomly oriented, so the fluid is superparamagnetic — strongly magnetized in an applied field, with essentially no remanence when the field is removed. It stays a liquid throughout.
Apply a sufficiently strong field perpendicular to a free surface and the flat surface abruptly breaks into a field of sharp peaks. This is the normal-field instability, described by Ronald Rosensweig and Mark Cowley in 1967. It is a competition between three energies:
- Magnetic energy — destabilizing. Magnetized fluid is drawn toward regions of higher field. A bump on the surface concentrates flux at its tip, which pulls more fluid up into the bump, which concentrates the flux further. Positive feedback.
- Gravity — stabilizing. Raising fluid above the mean level costs potential energy
ρgh, penalizing tall spikes. - Surface tension — stabilizing. Any corrugation increases surface area, costing energy
σper unit area, and it penalizes short-wavelength ripples hardest.
Because gravity suppresses long wavelengths and surface tension suppresses short ones, the instability first appears at an intermediate wavelength — the capillary length scale λ_c = 2π√(σ/ρg), a few millimetres for a typical oil-based ferrofluid, which is exactly the observed spike spacing. Below a critical magnetization the two stabilizing terms win and the surface stays flat; above it a band of wavelengths grows and the peaks erupt. The threshold condition is M_c² = (2/μ₀)(1 + 1/r_μ)·√(ρgσ), where r_μ is a permeability ratio — note that it depends on the geometric mean of gravity and surface tension, the two things holding the surface down.
The spikes settle into a hexagonal lattice for a reason worth stating precisely. The linear stability analysis picks out a preferred wavenumber but says nothing about which pattern of that wavenumber wins; that is decided by the nonlinear terms. In this system the quadratic term in the amplitude expansion is nonzero, and a nonzero quadratic term generically favours the resonant triad of three wavevectors at 120° whose sum is zero — which is precisely a hexagonal array. Hexagonal packing also happens to be the densest way to arrange peaks on a plane, minimizing energy for a given number of spikes. Push the field higher still and the pattern undergoes a further transition to squares.
Each individual spike is a static equilibrium, not a splash: the fluid is continuously balancing magnetic stress against the Laplace pressure of the curved tip and the weight of the raised column. The same fluids are genuinely useful — they seal rotating shafts in hard drives and vacuum feedthroughs, damp voice coils in loudspeakers, and have been trialled as drug-delivery and hyperthermia carriers in medicine.
Reading the four render layers
- Field lines: streamlines integrated with RK4 from an even ring of seeds around each source, with a step budget and termination when a line exits the canvas or re-enters a source. Arrowheads mark direction — always N to S outside a magnet.
- Iron filings: thousands of short segments, each aligned with the local B direction and faded by log|B|. This is the closest analogue to the classic schoolroom photograph, where each filing becomes a tiny induced dipole and torques into alignment. Turn on spikes to elongate the filings in intense regions.
- Arrow grid: a fixed lattice sampled directly from the superposed field, with both length and hue driven by log|B| — cyan for weak, amber for strong. Useful for spotting null points, where the arrows shrink to nothing.
- Heatmap: per-pixel |B| rendered into a reduced-resolution ImageData buffer and scaled up, giving a smooth glow that shows the overall energy landscape at a glance.
- Superposition: every layer reads the same field, which is the plain vector sum of all sources. Magnetostatics is linear in the sources, so adding a tenth magnet never changes what the first nine contribute — it only adds to it.