Prompt specification
Build or customize the Three.js 3D scene "Magnet and stationary coil model" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Magnet and stationary coil model
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/magnet-and-stationary-coil-model-x1633
Scene Description Prompt:
Build a coil with a movable bar-magnet proxy and a zero-centered indicator; show induced voltage only while the modeled magnetic flux changes. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (magnet-and-stationary-coil-model-x1633):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Electromagnetic Induction — Magnet and Coil</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 24, 39, 0.86);
--panel-border: rgba(104, 221, 255, 0.2);
--text: #eaf7ff;
--muted: #86a9bd;
--cyan: #53dcff;
--green: #42f5a1;
--amber: #ffd166;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.card {
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 16px;
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#titleCard {
position: fixed;
z-index: 3;
top: 18px;
left: 18px;
width: min(355px, calc(100vw - 36px));
padding: 17px 19px;
pointer-events: none;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 7px;
font-size: clamp(20px, 2.5vw, 28px);
line-height: 1.08;
letter-spacing: -0.035em;
}
#titleCard p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
#gaugeCard {
position: fixed;
z-index: 3;
top: 18px;
right: 18px;
width: 330px;
padding: 17px 18px 16px;
pointer-events: none;
}
.gauge-heading,
.status,
.readout-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.gauge-heading {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.range {
color: var(--amber);
letter-spacing: 0.04em;
}
.dial {
position: relative;
height: 90px;
margin: 13px 2px 0;
border-bottom: 1px solid rgba(130, 185, 211, 0.18);
}
.dial::before {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 11px;
height: 1px;
background: linear-gradient(
90deg,
rgba(255, 92, 104, 0.4),
rgba(83, 220, 255, 0.28) 50%,
rgba(66, 245, 161, 0.4)
);
}
.zero-line {
position: absolute;
z-index: 1;
left: 50%;
bottom: 5px;
width: 1px;
height: 67px;
background: rgba(255, 209, 102, 0.46);
transform: translateX(-50%);
}
.tick {
position: absolute;
bottom: 11px;
height: 38px;
transform: translateX(-50%);
}
.tick b {
position: absolute;
bottom: 0;
left: 50%;
display: block;
width: 1px;
height: 9px;
background: #6f91a5;
transform: translateX(-50%);
}
.tick.major b {
height: 15px;
background: #c2d8e4;
}
.tick small {
position: absolute;
bottom: -20px;
left: 50%;
color: var(--muted);
font-size: 9px;
font-variant-numeric: tabular-nums;
transform: translateX(-50%);
}
.needle {
position: absolute;
z-index: 4;
left: 50%;
bottom: 10px;
width: 3px;
height: 61px;
border-radius: 4px;
background: linear-gradient(
to top,
var(--amber),
#fff0b0 72%,
#ffffff
);
box-shadow: 0 0 12px rgba(255, 209, 102, 0.45);
transform: rotate(0deg);
transform-origin: 50% 100%;
will-change: transform;
}
.needle::before {
content: "";
position: absolute;
top: -3px;
left: 50%;
width: 0;
height: 0;
border-right: 5px solid transparent;
border-bottom: 9px solid #fff4c5;
border-left: 5px solid transparent;
transform: translateX(-50%);
}
.pivot {
position: absolute;
z-index: 5;
left: 50%;
bottom: 5px;
width: 12px;
height: 12px;
border: 2px solid #172b3b;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 14px rgba(255, 209, 102, 0.42);
transform: translateX(-50%);
}
.readout-row {
margin-top: 27px;
}
#voltageValue {
color: var(--amber);
font-size: 30px;
font-weight: 750;
font-variant-numeric: tabular-nums;
letter-spacing: -0.045em;
}
.status {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
#statusLed {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 7px;
border-radius: 50%;
background: #3d5260;
box-shadow: 0 0 0 rgba(66, 245, 161, 0);
transition: background 100ms, box-shadow 100ms;
vertical-align: 1px;
}
#statusLed.on {
background: var(--green);
box-shadow: 0 0 12px rgba(66, 245, 161, 0.8);
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 13px;
}
.metric {
padding: 9px 10px;
border: 1px solid rgba(113, 183, 214, 0.12);
border-radius: 10px;
background: rgba(2, 11, 20, 0.26);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.model-note {
margin: 12px 1px 0;
color: #6f91a5;
font-size: 10px;
line-height: 1.45;
}
#controls {
position: fixed;
z-index: 4;
right: 18px;
bottom: 18px;
left: 18px;
width: min(780px, calc(100vw - 36px));
margin: auto;
padding: 13px 15px;
}
.control-row {
display: flex;
align-items: center;
gap: 12px;
}
.control-label {
width: 112px;
flex: 0 0 auto;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#positionValue {
width: 46px;
color: var(--cyan);
font-size: 12px;
font-variant-numeric: tabular-nums;
text-align: right;
}
input[type="range"] {
width: 100%;
min-width: 80px;
accent-color: var(--cyan);
cursor: ew-resize;
}
button {
min-height: 35px;
padding: 0 13px;
border: 1px solid rgba(108, 211, 242, 0.22);
border-radius: 9px;
background: rgba(19, 45, 63, 0.9);
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 700;
white-space: nowrap;
cursor: pointer;
transition: background 120ms, border-color 120ms, transform 120ms;
}
button:hover {
border-color: rgba(108, 211, 242, 0.55);
background: rgba(27, 62, 84, 0.95);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(83, 220, 255, 0.45);
background: rgba(25, 115, 145, 0.36);
color: #bcefff;
}
.button-row {
display: flex;
gap: 7px;
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid rgba(113, 183, 214, 0.1);
}
#hint {
position: fixed;
z-index: 2;
bottom: 24px;
left: 22px;
color: rgba(173, 207, 223, 0.67);
font-size: 10px;
line-height: 1.55;
pointer-events: none;
}
#hint kbd {
padding: 2px 5px;
border: 1px solid rgba(173, 207, 223, 0.24);
border-radius: 4px;
color: #c9e4f2;
font: inherit;
}
#loading {
position: fixed;
z-index: 10;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--cyan);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
@media (max-width: 780px) {
#titleCard {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px 15px;
}
#titleCard p {
display: none;
}
#gaugeCard {
top: 104px;
right: 10px;
width: 280px;
padding: 13px 14px;
}
#gaugeCard .model-note {
display: none;
}
#controls {
right: 10px;
bottom: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 11px;
}
.control-label {
width: 90px;
}
.button-row {
overflow-x: auto;
}
#hint {
display: none;
}
}
@media (max-width: 480px) {
#gaugeCard {
width: calc(100vw - 20px);
}
.metrics {
display: none;
}
.control-row {
gap: 8px;
}
.control-label {
width: 76px;
font-size: 9px;
}
#positionValue {
width: 38px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<section id="titleCard" class="card">
<div class="eyebrow">Interactive induction proxy</div>
<h1>Magnet, Coil & Flux</h1>
<p>
Drag the bar magnet through the coil. The voltage appears only when
the modeled magnetic flux is changing.
</p>
</section>
<section id="gaugeCard" class="card">
<div class="gauge-heading">
<span>Induced voltage</span>
<span class="range">±8 mV</span>
</div>
<div class="dial">
<div class="zero-line"></div>
<div id="gaugeTicks"></div>
<div id="needle" class="needle"></div>
<div class="pivot"></div>
</div>
<div class="readout-row">
<div id="voltageValue">0.0 mV</div>
<div class="status">
<span><i id="statusLed"></i><span id="statusText">No flux change</span></span>
</div>
</div>
<div class="metrics">
<div class="metric">
<span>Modeled flux</span>
<strong id="fluxValue">0.000 mWb</strong>
</div>
<div class="metric">
<span>Magnet position</span>
<strong id="meterPosition">−2.35 u</strong>
</div>
</div>
<p class="model-note">
Dipole-field proxy with 9 turns.<br>
ε = −dΦ/dt; no persistent voltage at rest.
</p>
</section>
<section id="controls" class="card">
<div class="control-row">
<label class="control-label" for="positionSlider">Magnet position</label>
<input
id="positionSlider"
type="range"
min="-2.8"
max="2.8"
step="0.01"
value="-2.35"
aria-label="Magnet position"
>
<output id="positionValue" for="positionSlider">−2.35</output>
</div>
<div class="button-row">
<button id="sweepButton" class="primary" type="button">Auto sweep</button>
<button id="centerButton" type="button">Center magnet</button>
<button id="cameraButton" type="button">Reset camera</button>
</div>
</section>
<div id="hint">
Drag magnet: move · Drag background: orbit · Right-drag: pan · Wheel: zoom<br>
<kbd>←</kbd> <kbd>→</kbd> move magnet · <kbd>Space</kbd> auto sweep
</div>
<div id="loading">Loading Three.js scene…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Application constants and DOM
// ---------------------------------------------------------------------
const FULL_SCALE_MV = 8;
const MAX_NEEDLE_ANGLE = 55;
const AXIS_Y = 0.25;
const MAGNET_MIN = -2.8;
const MAGNET_MAX = 2.8;
const AUTO_AMPLITUDE = 2.45;
const AUTO_ANGULAR_SPEED = 0.9;
const viewport = document.getElementById("viewport");
const needle = document.getElementById("needle");
const voltageValue = document.getElementById("voltageValue");
const statusLed = document.getElementById("statusLed");
const statusText = document.getElementById("statusText");
const fluxValue = document.getElementById("fluxValue");
const meterPosition = document.getElementById("meterPosition");
const positionValue = document.getElementById("positionValue");
const positionSlider = document.getElementById("positionSlider");
const sweepButton = document.getElementById("sweepButton");
const centerButton = document.getElementById("centerButton");
const cameraButton = document.getElementById("cameraButton");
for (let i = 0; i <= 8; i++) {
const value = -FULL_SCALE_MV + (i / 8) * FULL_SCALE_MV * 2;
const tick = document.createElement("div");
const major = i === 0 || i === 4 || i === 8;
tick.className = `tick${major ? " major" : ""}`;
tick.style.left = `${(i / 8) * 100}%`;
tick.innerHTML = "<b></b>";
if (major) {
const label = document.createElement("small");
label.textContent =
value > 0 ? `+${value}` : value === 0 ? "0" : `${value}`;
tick.appendChild(label);
}
document.getElementById("gaugeTicks").appendChild(tick);
}
// ---------------------------------------------------------------------
// Renderer, camera, and lighting
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 10, 21);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
60
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance",
});
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional coil and movable bar magnet"
);
const hemi = new THREE.HemisphereLight(0x8edfff, 0x152235, 1.7);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xfff1d8, 3.2);
keyLight.position.set(4.5, 7.5, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x35d6ff, 1.8);
rimLight.position.set(-5, 3, -5);
scene.add(rimLight);
const coilLight = new THREE.PointLight(0x35d5ff, 7, 7, 2);
coilLight.position.set(0, 0.9, 1.2);
scene.add(coilLight);
// ---------------------------------------------------------------------
// Shared materials and geometry helpers
// ---------------------------------------------------------------------
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x142b3a,
roughness: 0.72,
metalness: 0.35,
flatShading: true,
});
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x0d1d2a,
roughness: 0.88,
metalness: 0.18,
flatShading: true,
});
const copperMaterial = new THREE.MeshStandardMaterial({
color: 0xc8783c,
roughness: 0.28,
metalness: 0.78,
emissive: 0x21d8ff,
emissiveIntensity: 0,
flatShading: true,
});
const redMaterial = new THREE.MeshStandardMaterial({
color: 0xe63e4f,
roughness: 0.38,
metalness: 0.18,
flatShading: true,
});
const blueMaterial = new THREE.MeshStandardMaterial({
color: 0x2879df,
roughness: 0.38,
metalness: 0.18,
flatShading: true,
});
const cyanBasicMaterial = new THREE.MeshBasicMaterial({
color: 0x53dcff,
transparent: true,
opacity: 0.19,
depthWrite: false,
});
function addBox(
width,
height,
depth,
material,
x,
y,
z,
parent = scene
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function createTextPlane(
text,
width,
height,
color = "#dff7ff",
fontSize = 100
) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
context.font = `800 ${fontSize}px ui-monospace, SFMono-Regular, Menlo, monospace`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false,
side: THREE.DoubleSide,
});
return new THREE.Mesh(new THREE.PlaneGeometry(width, height), material);
}
function createTextSprite(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 128, 128);
context.fillStyle = color;
context.font = "900 84px ui-sans-serif, system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 64, 67);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false,
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.46, 0.46, 1);
return sprite;
}
// ---------------------------------------------------------------------
// Ground, rail, supports, and coil
// ---------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(30, 18),
new THREE.MeshStandardMaterial({
color: 0x07121e,
roughness: 1,
metalness: 0,
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -1.26;
ground.receiveShadow = true;
scene.add(ground);
addBox(9.1, 0.18, 3.2, platformMaterial, 0, -1.13, 0);
const grid = new THREE.GridHelper(9, 18, 0x23506a, 0x132c3d);
grid.position.y = -1.032;
grid.material.transparent = true;
grid.material.opacity = 0.3;
scene.add(grid);
addBox(7.4, 0.065, 0.15, darkMaterial, 0, -0.965, 0);
for (let x = -3; x <= 3; x++) {
addBox(0.025, 0.035, 0.38, darkMaterial, x, -0.965, 0);
}
// Rear support posts.
addBox(0.12, 1.25, 0.12, darkMaterial, -0.58, -0.36, -0.73);
addBox(0.12, 1.25, 0.12, darkMaterial, 0.58, -0.36, -0.73);
addBox(1.28, 0.10, 0.12, darkMaterial, 0, -0.98, -0.73);
const coilGroup = new THREE.Group();
coilGroup.position.y = AXIS_Y;
scene.add(coilGroup);
const coilTurns = 9;
const coilRadius = 0.76;
for (let i = 0; i < coilTurns; i++) {
const x = -0.43 + (i / (coilTurns - 1)) * 0.86;
const turn = new THREE.Mesh(
new THREE.TorusGeometry(coilRadius, 0.047, 6, 28),
copperMaterial
);
turn.rotation.y = Math.PI / 2;
turn.position.x = x;
turn.castShadow = true;
turn.receiveShadow = true;
coilGroup.add(turn);
}
// Dark structural end rings.
for (const x of [-0.58, 0.58]) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.82, 0.035, 5, 28),
darkMaterial
);
ring.rotation.y = Math.PI / 2;
ring.position.x = x;
ring.castShadow = true;
coilGroup.add(ring);
}
// ---------------------------------------------------------------------
// Movable bar-magnet proxy
// ---------------------------------------------------------------------
const magnetGroup = new THREE.Group();
magnetGroup.position.y = AXIS_Y;
scene.add(magnetGroup);
const magnetHitTargets = [];
const redHalf = addBox(
1.12,
0.52,
0.52,
redMaterial,
0.59,
0,
0,
magnetGroup
);
magnetHitTargets.push(redHalf);
const blueHalf = addBox(
1.12,
0.52,
0.52,
blueMaterial,
-0.59,
0,
0,
magnetGroup
);
magnetHitTargets.push(blueHalf);
const seam = addBox(
0.075,
0.56,
0.56,
darkMaterial,
0,
0,
0,
magnetGroup
);
magnetHitTargets.push(seam);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(2.36, 0.57, 0.57)),
new THREE.LineBasicMaterial({
color: 0xe4f8ff,
transparent: true,
opacity: 0.34,
})
);
magnetGroup.add(outline);
// Field-envelope proxy rings.
for (const x of [-0.58, 0, 0.58]) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.013, 3, 20),
cyanBasicMaterial
);
ring.rotation.y = Math.PI / 2;
ring.position.x = x;
magnetGroup.add(ring);
}
const northLabel = createTextSprite("N", "#ffb0b8");
northLabel.position.set(0.72, 0.58, 0);
magnetGroup.add(northLabel);
const southLabel = createTextSprite("S", "#9cc8ff");
southLabel.position.set(-0.72, 0.58, 0);
magnetGroup.add(southLabel);
// A larger invisible hit volume makes the proxy easy to grab.
const magnetHitProxy = new THREE.Mesh(
new THREE.BoxGeometry(2.7, 0.9, 0.9),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false,
})
);
magnetGroup.add(magnetHitProxy);
magnetHitTargets.push(magnetHitProxy);
// ---------------------------------------------------------------------
// In-scene zero-centered indicator
// ---------------------------------------------------------------------
const indicatorBoard = new THREE.Group();
indicatorBoard.position.set(2.45, 0.52, -1.45);
indicatorBoard.rotation.y = -0.08;
scene.add(indicatorBoard);
addBox(
2.7,
1.45,
0.14,
darkMaterial,
0,
0,
0,
indicatorBoard
);
addBox(
2.54,
1.29,
0.025,
platformMaterial,
0,
0,
0.083,
indicatorBoard
);
addBox(
0.12,
0.88,
0.12,
darkMaterial,
0,
-1.13,
-0.08,
indicatorBoard
);
const boardTitle = createTextPlane(
"INDUCED VOLTAGE",
2.12,
0.29,
"#75dfff",
82
);
boardTitle.position.set(0, 0.46, 0.112);
indicatorBoard.add(boardTitle);
addBox(
2.04,
0.018,
0.022,
darkMaterial,
0,
-0.05,
0.13,
indicatorBoard
);
for (let i = 0; i <= 8; i++) {
const x = -1 + (i / 8) * 2;
const major = i === 0 || i === 4 || i === 8;
addBox(
major ? 0.026 : 0.017,
major ? 0.16 : 0.105,
0.025,
major ? redMaterial : darkMaterial,
x,
-0.05,
0.145,
indicatorBoard
);
}
addBox(
0.025,
0.23,
0.028,
new THREE.MeshBasicMaterial({ color: 0xffd166 }),
0,
-0.04,
0.16,
indicatorBoard
);
for (const [text, x] of [
["−8", -1],
["0", 0],
["+8", 1],
]) {
const label = createTextPlane(text, 0.31, 0.17, "#91afbf", 100);
label.position.set(x, -0.27, 0.16);
indicatorBoard.add(label);
}
const indicatorNeedlePivot = new THREE.Group();
indicatorNeedlePivot.position.set(0, -0.05, 0.18);
indicatorBoard.add(indicatorNeedlePivot);
const indicatorNeedle = addBox(
0.034,
0.72,
0.025,
new THREE.MeshBasicMaterial({ color: 0xffd166 }),
0,
0.36,
0,
indicatorNeedlePivot
);
indicatorNeedle.castShadow = false;
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 0.045, 12),
new THREE.MeshBasicMaterial({ color: 0xffdf89 })
);
hub.rotation.x = Math.PI / 2;
hub.position.set(0, -0.05, 0.205);
indicatorBoard.add(hub);
const boardLed = new THREE.Mesh(
new THREE.SphereGeometry(0.055, 8, 6),
new THREE.MeshBasicMaterial({ color: 0x334652 })
);
boardLed.position.set(1.12, 0.45, 0.17);
indicatorBoard.add(boardLed);
// Dynamic 3D numeric readout.
const valueCanvas = document.createElement("canvas");
valueCanvas.width = 512;
valueCanvas.height = 128;
const valueContext = valueCanvas.getContext("2d");
const valueTexture = new THREE.CanvasTexture(valueCanvas);
valueTexture.colorSpace = THREE.SRGBColorSpace;
const valuePlane = new THREE.Mesh(
new THREE.PlaneGeometry(1.35, 0.34),
new THREE.MeshBasicMaterial({
map: valueTexture,
transparent: true,
depthWrite: false,
toneMapped: false,
})
);
valuePlane.position.set(0, -0.49, 0.17);
indicatorBoard.add(valuePlane);
let lastBoardValue = "";
function updateBoardValue(text) {
if (text === lastBoardValue) return;
lastBoardValue = text;
valueContext.clearRect(0, 0, 512, 128);
valueContext.fillStyle = "#ffd166";
valueContext.font = "800 78px ui-monospace, SFMono-Regular, Menlo, monospace";
valueContext.textAlign = "center";
valueContext.textBaseline = "middle";
valueContext.fillText(text, 256, 64);
valueTexture.needsUpdate = true;
}
updateBoardValue("0.0 mV");
// ---------------------------------------------------------------------
// Magnetic-flux model
//
// Axial field of a dipole-like bar magnet:
// Bx(x) ∝ x / (x² + a²)^(5/2)
//
// Flux through N turns:
// Φ(x) = N A Bx(x)
//
// Induced voltage:
// ε = −dΦ/dt
// ---------------------------------------------------------------------
const COIL_TURNS = 9;
const COIL_AREA = Math.PI * coilRadius * coilRadius;
const MAGNET_MOMENT = 70;
const DIPOLE_SOFTENING = 0.34;
const MU_0_OVER_4_PI = 1e-7;
function fluxAt(x) {
const softenedDistance =
x * x + DIPOLE_SOFTENING * DIPOLE_SOFTENING;
const axialField =
(MU_0_OVER_4_PI *
2 *
MAGNET_MOMENT *
x) /
Math.pow(softenedDistance, 2.5);
return COIL_TURNS * COIL_AREA * axialField;
}
// ---------------------------------------------------------------------
// Custom camera controls and magnet dragging
// ---------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0, 0),
radius: 7.5,
theta: 0.72,
phi: 1.13,
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
const cosPhi = Math.cos(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * cosPhi,
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.target.set(0, 0, 0);
cameraState.radius = 7.5;
cameraState.theta = 0.72;
cameraState.phi = 1.13;
updateCamera();
}
updateCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-AXIS_Y
);
const planePoint = new THREE.Vector3();
let draggingMagnet = false;
let orbiting = false;
let panning = false;
let previousPointerX = 0;
let previousPointerY = 0;
let magnetDragOffset = 0;
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pointerOnAxisPlane() {
raycaster.setFromCamera(pointer, camera);
return raycaster.ray.intersectPlane(dragPlane, planePoint);
}
function pickMagnet() {
scene.updateMatrixWorld(true);
raycaster.setFromCamera(pointer, camera);
return raycaster.intersectObjects(magnetHitTargets, false).length > 0;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
event.preventDefault();
updatePointer(event);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
if (event.button === 0 && pickMagnet()) {
draggingMagnet = true;
stopAutoSweep();
if (pointerOnAxisPlane()) {
magnetDragOffset = magnetX - planePoint.x;
} else {
magnetDragOffset = 0;
}
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "ew-resize";
return;
}
if (event.button === 0) {
orbiting = true;
} else if (event.button === 2) {
panning = true;
}
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
updatePointer(event);
if (draggingMagnet) {
if (pointerOnAxisPlane()) {
targetX = THREE.MathUtils.clamp(
planePoint.x + magnetDragOffset,
MAGNET_MIN,
MAGNET_MAX
);
}
return;
}
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
if (orbiting) {
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + deltaY * 0.005,
0.35,
1.45
);
updateCamera();
} else if (panning) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const scale = cameraState.radius * 0.0015;
cameraState.target
.addScaledVector(right, -deltaX * scale)
.addScaledVector(up, deltaY * scale);
cameraState.target.y = THREE.MathUtils.clamp(
cameraState.target.y,
-1.1,
1.8
);
updateCamera();
} else {
renderer.domElement.style.cursor = pickMagnet()
? "ew-resize"
: "grab";
}
previousPointerX = event.clientX;
previousPointerY = event.clientY;
});
function endPointer(event) {
draggingMagnet = false;
orbiting = false;
panning = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "grab";
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
4.6,
12
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Motion state and controls
// ---------------------------------------------------------------------
let magnetX = -2.35;
let targetX = magnetX;
let autoSweep = false;
let autoStartTime = 0;
let autoStartPhase = 0;
function stopAutoSweep() {
if (!autoSweep) return;
autoSweep = false;
sweepButton.textContent = "Auto sweep";
}
function toggleAutoSweep() {
if (autoSweep) {
stopAutoSweep();
return;
}
autoSweep = true;
autoStartTime = performance.now();
const normalized = THREE.MathUtils.clamp(
magnetX / AUTO_AMPLITUDE,
-0.95,
0.95
);
autoStartPhase = Math.asin(normalized);
if (Math.abs(magnetX) > AUTO_AMPLITUDE * 0.95) {
magnetX = AUTO_AMPLITUDE * 0.95;
targetX = magnetX;
}
sweepButton.textContent = "Pause sweep";
}
positionSlider.addEventListener("input", () => {
stopAutoSweep();
targetX = Number(positionSlider.value);
});
centerButton.addEventListener("click", () => {
stopAutoSweep();
targetX = 0;
});
cameraButton.addEventListener("click", resetCamera);
sweepButton.addEventListener("click", toggleAutoSweep);
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "ArrowLeft" || event.code === "ArrowRight") {
event.preventDefault();
stopAutoSweep();
const direction = event.code === "ArrowLeft" ? -1 : 1;
const step = event.shiftKey ? 0.35 : 0.12;
targetX = THREE.MathUtils.clamp(
targetX + direction * step,
MAGNET_MIN,
MAGNET_MAX
);
}
if (event.code === "Space") {
event.preventDefault();
toggleAutoSweep();
}
});
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
// ---------------------------------------------------------------------
// Animation and indicator synchronization
// ---------------------------------------------------------------------
let previousTime = performance.now();
let previousFlux = fluxAt(magnetX);
let inducedMillivolts = 0;
let fluxChanged = false;
function animate(now) {
const deltaTime = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (autoSweep) {
const elapsed = (now - autoStartTime) / 1000;
targetX =
AUTO_AMPLITUDE *
Math.sin(autoStartPhase + elapsed * AUTO_ANGULAR_SPEED);
}
// Bound proxy speed so the displayed voltage remains readable.
const maximumStep = 4.8 * deltaTime;
const remaining = targetX - magnetX;
magnetX += THREE.MathUtils.clamp(
remaining,
-maximumStep,
maximumStep
);
if (Math.abs(targetX - magnetX) < 0.00001) {
magnetX = targetX;
}
magnetGroup.position.x = magnetX;
const currentFlux = fluxAt(magnetX);
const fluxDifference = currentFlux - previousFlux;
fluxChanged =
deltaTime > 0 && Math.abs(fluxDifference) > 1e-12;
inducedMillivolts = fluxChanged
? -(fluxDifference / deltaTime) * 1000
: 0;
previousFlux = currentFlux;
const normalizedVoltage = THREE.MathUtils.clamp(
inducedMillivolts / FULL_SCALE_MV,
-1,
1
);
const needleAngle = normalizedVoltage * MAX_NEEDLE_ANGLE;
needle.style.transform = `rotate(${needleAngle}deg)`;
indicatorNeedlePivot.rotation.z = THREE.MathUtils.degToRad(
-needleAngle
);
const signedVoltage = `${inducedMillivolts >= 0 ? "+" : "−"}${Math.abs(
inducedMillivolts
).toFixed(1)} mV`;
voltageValue.textContent = signedVoltage;
updateBoardValue(signedVoltage);
statusLed.classList.toggle("on", fluxChanged);
statusText.textContent = fluxChanged
? "Flux changing"
: "No flux change";
boardLed.material.color.setHex(
fluxChanged ? 0x42f5a1 : 0x334652
);
// The coil only glows while an induced voltage exists.
copperMaterial.emissiveIntensity = fluxChanged
? Math.min(Math.abs(inducedMillivolts) / FULL_SCALE_MV, 1) * 0.48
: 0;
const fluxMilliwebers = currentFlux * 1000;
fluxValue.textContent = `${fluxMilliwebers.toFixed(3)} mWb`;
const positionText = `${magnetX.toFixed(2)} u`;
positionValue.textContent = positionText;
meterPosition.textContent = positionText;
positionSlider.value = String(targetX);
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
document.getElementById("loading").style.display = "none";
</script>
</body>
</html>
```