Three.js Magnetic Field Lines (Bar Magnet Visualizer)

Trace magnetic field lines around bar magnets in Three.js with numerical integration, compare attracting, repelling and quadrupole arrangements, and watch particles flow from north to south.

Key topics: three.js magnetic field, field lines, bar magnet, electromagnetism, vector field, physics visualization

What this code does

- Gilbert Model: each magnet is two magnetic charges, so B(r) = Σ q(r − rᵢ)/|r − rᵢ|³.
- Line Tracing: seeds around every north pole are integrated with midpoint (RK2) steps along the normalized field until they hit a south pole.
- Color by Strength: line vertices are colored by log |B|, so you can see the strong field near the poles.
- Flow Particles: points slide along each traced polyline to show field direction (N → S outside the magnet).
- Configurations: attracting pairs connect lines between magnets, while repelling pairs create a neutral point between them.
- Controls: configuration, lines per pole, 2D/3D seeding, flow particles and speed, and a rotating magnet that re-traces live.

Continue Learning

JavaScript Implementation

ES6+
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 200)
camera.position.set(0, 4, 14)
camera.lookAt(0, 0, 0)
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(width, height)
document.querySelector('#app').appendChild(renderer.domElement)

// Bar magnet as two magnetic charges: north (+1) and south (−1)
const poles = [
  { p: new THREE.Vector3(1.2, 0, 0), q: 1 },
  { p: new THREE.Vector3(-1.2, 0, 0), q: -1 }
]

function field (r) {
  const b = new THREE.Vector3()
  poles.forEach(({ p, q }) => {
    const d = r.clone().sub(p)
    const len = Math.max(d.length(), 0.1)
    b.addScaledVector(d, q / (len * len * len))
  })
  return b
}

for (let i = 0; i < 24; i++) {
  const a = (i / 24) * Math.PI * 2
  const p = poles[0].p.clone().add(new THREE.Vector3(Math.cos(a), Math.sin(a), 0).multiplyScalar(0.2))
  const pts = [p.clone()]
  for (let s = 0; s < 800; s++) {
    p.addScaledVector(field(p).normalize(), 0.08)
    pts.push(p.clone())
    if (p.length() > 20 || p.distanceTo(poles[1].p) < 0.2) break
  }
  scene.add(new THREE.Line(
    new THREE.BufferGeometry().setFromPoints(pts),
    new THREE.LineBasicMaterial({ color: 0x60a5fa })
  ))
}
renderer.render(scene, camera)