### user
You are a code expert, please use your professional knowledge to generate accurate and professional responses. Be sure to ensure the generated code is executable for demonstration. Design a Millikan oil drop experiment simulation webpage that allows dynamic changes to the electric field voltage, oil drop height, and oil drop charge; the webpage needs to clearly display the height of two metal plates, with the lower metal plate's height defaulted to 0; the webpage should store multiple experiment records displayed in a list format.
### assistant · thinking
The user wants a Millikan oil drop experiment simulation webpage. Requirements:
- Dynamic changes to electric field voltage, oil drop height, oil drop charge
- Clearly display height of two metal plates, lower plate default height 0
- Store multiple experiment records displayed in list format
Let me design a single HTML file with canvas or DOM-based simulation.
Physics: Millikan oil drop experiment. Two horizontal plates, distance d apart. Voltage U applied across them creates E = U/d. Oil drop with charge q experiences:
- Gravity: mg downward
- Buoyancy (neglect or include)
- Electric force: qE (direction depends on sign of q and polarity)
- Drag: Stokes' law, F_d = 6πηrv
Terminal velocity when forces balance.
Let's keep it simpler but physically meaningful. We can simulate with velocity and drag.
Let me define:
- Plate separation d (mm) — but the requirement says "clearly display the height of two metal plates, with the lower metal plate's height defaulted to 0". So we have a coordinate system where lower plate y=0 (mm) and upper plate at y = h. The oil drop height is between 0 and h.
Hmm, "oil drop height" — the user wants to change oil drop height dynamically. So the drop's initial position can be set.
Actually maybe: plate height (lower plate at 0, upper plate at some height H). The oil drop height is its position. Let's make:
- Lower plate height = 0 (fixed, displayed)
- Upper plate height = H (adjustable, e.g., 5.0 mm... actually real Millikan uses ~ 1 cm). Let's use mm scale for display.
- Oil drop height adjustable within [0, H]
Let's use a scale: 1 mm = some pixels.
Simulation:
- Plate separation d = upperPlateHeight - lowerPlateHeight (in mm)
- E = U / d (V/mm → convert to V/m: U / (d/1000) = 1000*U/d V/m)
- Radius r ~ 1e-6 m, density ρ = 900 kg/m³ (oil ~ 900)
- Mass m = (4/3)πr³ρ
- Charge q in units of e = 1.602e-19 C
- Stokes drag: F = 6πηrv, η = 1.81e-5 Pa·s
Forces in vertical (y up positive):
- Gravity: -mg
- Electric: qE (if q positive and upper plate positive... let's define E field downward or upward). Let's say voltage U > 0 means upper plate positive, field points downward (from + to -), so force on positive charge is downward. Hmm, let's just define: electric force = q * E_signed where E = -U/d * (down direction)... Let's simplify:
Let's define electric force F_e = q * U / d (in Newtons, with U in V, d in m). Positive U with positive q → upward force. That's a convention; document it.
Actually to be physically intuitive: If the upper plate is positive and the drop has negative charge, the drop is attracted upward. Let's just say the electric force is q*E with E = U/d, and positive q means the force is upward when U>0.
Drag: F_d = -6πηrv (opposing velocity).
Then a = (F_e - mg + F_d)/m ... need effective mass with buoyancy but let's ignore buoyancy for simplicity or include it.
The problem: real Millikan drops are tiny; with these numbers, terminal velocity is small. We need a time scaling for visualization. Let's compute.
r = 1e-6 m, ρ = 900 → m = 4/3 π (1e-6)³ * 900 = 4.18879e-18 * 900 = 3.77e-15 kg.
mg = 3.77e-15 * 9.8 = 3.69e-14 N.
6πηr = 6π * 1.81e-5 * 1e-6 = 3.412e-10.
Terminal velocity from gravity alone: v = mg/(6πηr) = 3.69e-14/3.412e-10 = 1.08e-4 m/s = 0.108 mm/s. OK.
Electric force needed to balance: qE = mg. With q = 5e (8e-19 C) and E = U/d with d = 5mm = 5e-3 m: E = U/5e-3 = 200U. qE = 8e-19 * 200 U = 1.6e-16 U. Set = 3.69e-14 → U = 230 V. Reasonable! Good.
So with d = 5 mm, U around a few hundred volts, charge a few e, things balance nicely.
Time scale: terminal velocity 0.1 mm/s means crossing 5 mm takes 50 s. That's slow for a demo. We can add a time scale factor (e.g., 10x) and label it. Or make the drop bigger. Let's add a "simulation speed" — actually the user didn't ask. Let's just use a time scale factor internally like 20x and mention it. Hmm, but that would make terminal velocity calculations still consistent visually.
Actually simpler: just scale time. Let's set TIME_SCALE = 20. So 1 real second = 20 simulated seconds. Then crossing takes 2.5 s. Good.
Hmm, but then the displayed velocity would be weird. We can just not display velocity, or display it in mm/s.
Alternatively, use a bigger drop: r = 2e-6 m → m = 8x, mg = 2.95e-13, drag coefficient 6.82e-10, terminal v = 4.3e-4 m/s = 0.43 mm/s. Still slow.
Let's just use TIME_SCALE. Fine.
Let me also handle: when the drop hits the plates, it stops (or bounces). Let's clamp at 0 and H, and set velocity to 0.
UI:
- Left: canvas with the two plates drawn, the oil drop, arrows for forces maybe.
- Right: controls
- Voltage slider (-1000 to 1000 V)
- Upper plate height slider (e.g., 2 to 10 mm)
- Oil drop height slider (0 to upper plate height) — actually maybe drag. Let's provide a slider but also it changes as it moves. Hmm, conflicting. Let's make the slider set the initial height when the drop is reset, and during simulation the slider updates to show the current height (read-only display)? Better: the "oil drop height" control sets the current position; if simulation is running, it gets overwritten. Let's have:
- A slider "Oil drop height" that sets the initial/current position. When the user drags it, the drop moves to that height and velocity resets.
- The slider value updates live during simulation.
That works nicely.
- Charge slider: -10e to +10e (integer multiples of e). Show in units of e.
- Buttons: Start/Pause, Reset, Record experiment (adds record), Clear records.
Records list: each record shows timestamp, U, plate height (d), drop height, charge, net force, terminal velocity, etc.
Let me now write the physics update.
Constants:
- η = 1.81e-5 Pa·s
- ρ_oil = 900 kg/m³ (but effective density minus air ~ 900 - 1.2, negligible)
- e = 1.602e-19 C
- g = 9.81 m/s²
Parameters (SI):
- radius r = 1e-6 m (fixed) — or make it adjustable? Not required. Keep fixed but display.
- d = plateSeparation in m = (upperHeight - lowerHeight)/1000
- E = U / d (V/m), sign convention: positive U → force on positive charge upward.
Forces (up positive):
F_e = q * E where E = U/d
F_g = -m g
F_d = -6πηr v
a = (F_e + F_g + F_d)/m
Update: v += a*dt_sim; y += v*dt_sim (y in meters, but let's keep y in mm for display: y_mm).
Let's work in SI then convert.
Let y_m (meters), height from lower plate. y_m = y_mm/1000.
dt_sim = dt_real * TIME_SCALE, capped.
Use fixed substeps for stability: dt_sim in small steps of max 0.001 s.
Actually with drag, time constant τ = m/(6πηr) = 3.77e-15/3.412e-10 = 1.1e-5 s. That's super small! So the drop reaches terminal velocity almost instantly. That means we need dt_sim < ~1e-6 to be stable... Hmm.
Let's use an analytic/steady-state approach instead: since drag time constant is tiny compared to everything, assume the drop is always at terminal velocity:
v_terminal = (F_e + F_g)/(6πηr)
That's much more stable and physically accurate for this regime.
So v = (qE - mg)/(6πηr) [m/s]
With qE = mg balance → v=0.
Let's compute magnitudes: qE max = 10e * (1000/0.005) = 10*1.602e-19*200000 = 3.2e-13 N. mg = 3.69e-14 N. So max v = (3.2e-13)/(3.412e-10) = 9.4e-4 m/s = 0.94 mm/s. OK so with 1000V it moves ~1mm/s. With TIME_SCALE = 20 → 20 mm/s on screen. Screen: 5mm plate separation maps to maybe 400 px → 80 px/mm. So 20mm/s * 80 = 1600 px/s. Too fast. Let's use TIME_SCALE = 5 → 5 mm/s → 400 px/s. Reasonable. Or TIME_SCALE = 3.
Hmm, let's make the scale adaptive. Let's just pick TIME_SCALE = 4.
Actually let's reconsider: we want visible motion. With U=500V, q=+3e: qE = 3*1.602e-19 * (500/0.005) = 4.806e-19 * 100000 = 4.806e-14 N. Net = 4.806e-14 - 3.69e-14 = 1.116e-14 N. v = 1.116e-14/3.412e-10 = 3.27e-5 m/s = 0.0327 mm/s. With TIME_SCALE=4 → 0.13 mm/s real-time... over 5 mm takes 38 s. Too slow.
Hmm. Let's increase TIME_SCALE to 20 → 0.65 mm/s → 7.7 s to cross 5mm. Acceptable.
But at 1000V it's 20x faster: 0.94mm/s*20 = 18.8 mm/s → 5mm in 0.27s. Fast but fine.
OK let's use TIME_SCALE = 20. Good compromise. Actually maybe make it 15. Let's go with 20.
Hmm, but wait — the drag-based terminal velocity approach makes it feel like a "viscous" environment. That's fine and physical.
Actually, let's add a bit of inertia for visual smoothness? No, keep it simple: velocity follows terminal velocity with a small smoothing (lerp) to avoid jumps. Actually just use terminal velocity directly — it's fine.
Hmm, but there's an issue: if the drop is at rest on the plate and voltage changes, it starts moving instantly. That's fine.
Let me reconsider using real dynamics with a fixed small dt. m/(6πηr) = 1.1e-5 s. With TIME_SCALE 20 and dt_real = 1/60 s, dt_sim = 0.33 s. Way too big. So analytic terminal velocity is the way. Good.
Actually, I could use a smoothed approach: v += (v_terminal - v) * (1 - exp(-dt_sim/τ)) where τ = m/(6πηr). Since τ is tiny, this is essentially v = v_terminal. Fine, just use v = v_terminal.
Now, let's also add a "settling" behavior — no.
Let's now design the canvas.
Canvas size: let's say 420 x 560 (or responsive).
Layout: vertical axis. Lower plate at bottom (y=0 mm), upper plate at top (y = H mm).
Drawing:
- Vertical axis on the left with tick marks in mm.
- Lower plate: a horizontal thick bar at the bottom, labeled "下极板 y = 0.00 mm".
- Upper plate: horizontal thick bar at position corresponding to H, labeled "上极板 y = H.xx mm".
- Oil drop: a circle at position y.
- Force arrows next to the drop? Maybe show a small legend with force values.
Scale: pixel per mm = (canvasHeight - margins) / maxPlateHeight. Let's use a fixed max of 10 mm for the scale so the plates move visibly. Actually the plate separation changes when you move the upper plate. Let's fix the drawing scale to 10 mm = full height. Then upper plate at 5mm is halfway.
Hmm, but then the drop region is only half the canvas. Let's set max plate height = 10 mm and the canvas drawing area maps 0..10 mm. That's fine.
Actually, we could auto-scale but then moving the upper plate would look weird. Fixed scale is better for "clearly display the height of two metal plates".
Let's use range: upper plate height 2–10 mm, default 5 mm. Lower plate 0.
Wait, but the user says "clearly display the height of two metal plates, with the lower metal plate's height defaulted to 0". Maybe they want the lower plate height adjustable too, defaulting to 0? Hmm. "下金属板高度默认为0" — I think it means the lower plate is at height 0 by default. Could be adjustable. Let's make the lower plate fixed at 0 and clearly labeled. Actually, to be safe, let's make it fixed at 0.00 mm and prominently displayed. Hmm, but "dynamic changes to ... oil drop height" — the drop height is what changes.
Actually, let me allow the lower plate to be fixed at 0 (not adjustable) since it says "defaulted to 0". Simpler and matches "clearly display the height of two metal plates".
Hmm, I'll just fix it at 0 and show it clearly. Good.
Now, voltage sign: Let's have a "polarity" concept — U from -1000 to +1000 V. Positive U means upper plate is positive. A negative oil drop (typical) would then be attracted upward. Let's define electric force on charge q: F = qE, with E = U/d pointing...
Let's set: E vector points downward when U > 0 (from + upper plate to - lower plate). Then force on charge q is qE_vector. If q < 0, force is upward.
So in scalar (up-positive) terms: F_e = -q * (U/d) ... hmm confusing.
Let's just define F_e (upward positive) = -q*U/d. Then for q = -5e and U = +500: F_e = +5e*500/d > 0, upward. Good, that matches physics (negative charge attracted to positive upper plate).
Hmm, but for a user setting "charge = +5e" and "voltage = +500", they'd expect the drop to go up? Not necessarily. Let's just label clearly.
Actually, let's simplify for the user: define "Electric field force = q × U / d, positive = upward". Then display it. Hmm, but that's not physically standard.
I'll go with the physical convention and label the polarity clearly: "上极板接正极" when U>0.
F_e_up = -q * U / d.
Hmm, that might confuse. Let me think about what's most intuitive. In the real Millikan experiment, the drop is negatively charged and the upper plate is positive, so the drop rises. So with q = -5e and U = +500, the drop rises. That's the standard setup. Good, let's use the physical convention.
Wait, but actually in the classic Millikan setup, the plates are horizontal, the upper plate has a hole for the droplets, and the electric field is applied to hold the drop stationary or move it up/down.
OK. Let's go with F_e_up = -q*U/d.
Hmm, actually let me reconsider once more. Standard: E field between plates points from + to -. If upper plate is +, E points down (negative y). Force on charge q: F = qE. If q is negative, F = -q|E| * (down) = up. Yes.
So F_e_up = -q * (U/d). With U>0 (upper +), E points down, magnitude U/d.
Great.
Now the default: q = -5e, U = +? Let's find balance: need -q*U/d = mg → 5*1.602e-19 * U/0.005 = 3.69e-14 → 8.01e-19*200U = 3.69e-14 → 1.602e-16 U = 3.69e-14 → U = 230 V.
So U = 230 V balances q = -5e. Let's set default U = 300 V so the drop rises slowly. Or 200 V so it falls slowly. Let's default U = 250 V.
Hmm, let's just pick defaults: U = 300 V, q = -5e, upper plate height = 5 mm, drop height = 2.5 mm.
Let's compute: F_e = 5*1.602e-19 * 300/0.005 = 8.01e-19 * 60000 = 4.806e-14 N up. mg = 3.69e-14 down. Net = 1.116e-14 up. v = 3.27e-5 m/s = 0.0327 mm/s. With TIME_SCALE=20 → 0.654 mm/s. Crosses 2.5 mm in ~3.8 s.
Now the records. Each record: index, timestamp, U, plate separation, drop height, charge (in e), net force, terminal velocity, direction.
Let me build the UI with a nice modern design.
Let me write the code.
```html
密立根油滴实验模拟
...
```
Let me write out the structure:
```
...
...
```
Let me write the CSS for a dark-ish scientific look.
Now the JS.
State:
```js
const S = {
U: 300, // V
upperH: 5.0, // mm
lowerH: 0.0, // mm (fixed)
dropH: 2.5, // mm
chargeE: -5, // in units of e
running: false,
v: 0, // m/s
records: [],
t: 0
};
```
Constants:
```js
const E_CHARGE = 1.602e-19;
const G = 9.81;
const ETA = 1.81e-5;
const R_DROP = 1e-6;
const RHO_OIL = 900;
const MASS = 4/3*Math.PI*R_DROP**3*RHO_OIL;
const DRAG_C = 6*Math.PI*ETA*R_DROP;
const TIME_SCALE = 20;
```
Physics function:
```js
function physics() {
const d = (S.upperH - S.lowerH) / 1000; // m
const E = S.U / d; // V/m, positive means downward field (upper plate positive)
const q = S.chargeE * E_CHARGE; // C
const Fe = -q * E; // upward positive
const Fg = -MASS * G;
const Fnet = Fe + Fg;
const v = Fnet / DRAG_C; // m/s, upward positive
return {d, E, q, Fe, Fg, Fnet, v};
}
```
Update loop:
```js
let last = performance.now();
function loop(now) {
const dtReal = Math.min((now - last)/1000, 0.05);
last = now;
if (S.running) {
const p = physics();
const dtSim = dtReal * TIME_SCALE;
S.dropH += p.v * 1000 * dtSim; // v m/s -> mm/s
// clamp
if (S.dropH <= S.lowerH) { S.dropH = S.lowerH; }
if (S.dropH >= S.upperH) { S.dropH = S.upperH; }
}
render();
requestAnimationFrame(loop);
}
```
Wait — if the drop is clamped, velocity should be zeroed but it doesn't matter since we recompute each frame.
Hmm, but if the drop is resting on the bottom plate and Fnet > 0, it should rise. It will, since dropH increases from 0. Good.
But if dropH = upperH and Fnet > 0, it stays clamped. Fine.
Render:
- Clear canvas
- Compute scale
- Draw axis, plates, drop, force arrows
Let me set up the canvas with devicePixelRatio handling.
Canvas layout:
- padding top 40, bottom 50, left 70, right 40
- drawHeight = H - padTop - padBottom
- mmToPx: we map 0..MAX_MM (10) to bottom..top.
pxPerMm = drawHeight / MAX_MM
y_px(mm) = padTop + drawHeight - mm * pxPerMm
Wait: mm=0 → padTop + drawHeight = bottom. mm=10 → padTop. Good.
Draw:
- Axis line at x = padLeft - 15 (a vertical line with ticks every 1 mm)
- Grid lines light
- Lower plate: rect from x=padLeft to x=W-padRight, at y=0, thickness 10px
- Upper plate: same at y=upperH
- Labels
- Drop: circle at (centerX, y_px(dropH)), radius ~9px. Draw with a gradient.
- Force arrows: from the drop, draw arrow up/down proportional to forces? Maybe draw two arrows: electric force and gravity. Could be cluttered. Let's draw a net force arrow to the right of the drop, plus small text.
Actually let's draw force arrows to the left of the drop... hmm, the axis is on the left. Let's put force arrows to the right of the drop.
Let's draw:
- Gravity arrow (down, orange) length proportional to |Fg|
- Electric arrow (up or down, blue) length proportional to |Fe|
- Net arrow (green/red)
Scale: max force ~ 3.2e-13 N. Let's scale so 3.2e-13 → 60 px.
Hmm, might be cluttered. Let's just draw the net force arrow and a readout panel with numbers.
Actually let's draw both Fe and Fg as arrows, and the net as a text readout. Let me draw arrows anchored at the drop center, offset horizontally.
Simplify: Draw a vertical "force bar" on the right side of the canvas showing Fe and Fg magnitudes. Hmm.
Let's just do: arrows starting at drop center.
- Electric force arrow: from center, pointing up or down, length = |Fe| * scaleF, color #4da3ff.
- Gravity arrow: from center, pointing down, length = |Fg| * scaleF, color #ffa94d.
They'd overlap. Offset them: electric at x = cx + 14, gravity at x = cx - 14? But the drop is small. Let's put electric arrow at cx + 16 and gravity at cx + 40.
Hmm, let's do a cleaner approach: draw the arrows starting from the drop, but offset:
- Electric force: vertical line at x = cx + 18
- Gravity: vertical line at x = cx + 40
Actually, let me put force arrows to the left and right of the drop:
- Electric force arrow at x = cx - 22 (left)
- Gravity arrow at x = cx + 22 (right)
Hmm, gravity always points down, electric points up or down.
OK fine. Let's do that with labels.
Alternatively, keep it simple and clean: draw only the net force arrow next to the drop, plus numeric readouts in a panel. I think drawing both is more educational. Let's do both with small labels.
Let me now think about the readout panel below the canvas:
- 上极板高度: 5.00 mm
- 下极板高度: 0.00 mm
- 极板间距 d: 5.00 mm
- 电场强度 E: 60000 V/m
- 油滴高度: 2.50 mm
- 油滴速度: 0.65 mm/s (↑/↓/静止)
- 重力 Fg: 3.69e-14 N
- 电场力 Fe: 4.81e-14 N
- 合力 Fnet: 1.12e-14 N ↑
Good.
Now the controls:
1. 电场电压 U: range -1000 to 1000, step 10, default 300. Display value.
2. 上极板高度: range 2 to 10, step 0.1, default 5.
3. 油滴电荷量 q: range -10 to 10, step 1, default -5. Display in e and C.
4. 油滴高度: range 0 to upperH, step 0.01, default 2.5. This one updates live.
Buttons: 开始/暂停, 重置, 记录数据, 清空记录.
Wait, "油滴高度" slider: when the upper plate height changes, the max of this slider must update. And if dropH > upperH, clamp it.
Also, dragging the oil drop height slider should set the drop position. And during simulation, the slider position should update.
Implementation:
```js
dropHeightSlider.addEventListener('input', () => {
S.dropH = parseFloat(dropHeightSlider.value);
// optionally pause? no
});
```
And in render, set dropHeightSlider.value = S.dropH (if not being dragged). Actually setting value during input event could be janky. Let's just always set it in render — the value will be the same as what the user set, so it's fine.
Hmm, but if the user drags while running, the value gets overwritten. It's fine.
Now records. Each record:
```js
{
id, time: new Date().toLocaleTimeString(),
U, upperH, lowerH, d, dropH, chargeE, E, Fe, Fg, Fnet, v
}
```
Display in a list. Each item shows the key values.
Let's make the record list scrollable.
Also add a "记录数据" button that captures the current state.
Let me also add the ability to delete individual records? Not required. Add "清空记录".
Alright, let's write the code.
Also, I should add a chart? No, keep it focused.
Let me write the CSS.
```css
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Segoe UI', 'Microsoft YaHei', system-ui, sans-serif;
background: radial-gradient(circle at 20% 0%, #1b2a41, #0b1220 60%);
color: #e6edf7;
min-height: 100vh;
padding: 18px;
}
```
Layout: grid with two columns. Left flexible, right 380px.
Let me write it out fully now.
For the canvas, I'll use a fixed logical size (e.g., 480x620) and scale with CSS to fit.
Actually, let's make it responsive using ResizeObserver. Simpler: set canvas width/height attributes based on container size and redraw. Let me use a fixed aspect ratio with CSS `width: 100%; height: auto;` and set the internal resolution once with devicePixelRatio... but then it'd be blurry when scaled up.
Let's do a resize function that reads the container's clientWidth and sets the canvas resolution accordingly.
```js
function resize() {
const rect = wrap.getBoundingClientRect();
const w = rect.width;
const h = Math.max(420, Math.min(680, w * 1.25));
const dpr = window.devicePixelRatio || 1;
cv.width = w * dpr;
cv.height = h * dpr;
cv.style.width = w + 'px';
cv.style.height = h + 'px';
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
CW = w; CH = h;
}
```
Good.
Now render with CW, CH.
Let me define:
- padL = 78, padR = 30, padT = 46, padB = 60
- plotW = CW - padL - padR
- plotH = CH - padT - padB
- MAX_MM = 10 (or max(upperH + 1, 10)? Let's use a fixed 10 so the scale doesn't jump. But if upperH max is 10, the plate would be at the very top. Let's set MAX_MM = 11 and upper plate range 2-10.)
Hmm, let's use MAX_MM = 11.
pxPerMm = plotH / MAX_MM
yOf(mm) = padT + plotH - mm * pxPerMm
Center x: cx = padL + plotW/2.
Let's draw:
1. Background grid: horizontal lines every 1 mm, light.
2. Axis: vertical line at x = padL - 20, from yOf(0) to yOf(MAX_MM). Ticks and labels every 1 mm (label every 1 or 2 mm).
Actually let's put the axis at the left edge of the plot area, x = padL. And the plates span from padL to padL+plotW.
Hmm, let me put the axis just left of the plot: axisX = padL - 26.
Ticks: from axisX to axisX+6, label at axisX - 6 (right-aligned).
3. Plates:
- Lower plate at yOf(0): a rect with height 12, from padL to padL+plotW. Color: metallic gradient.
- Upper plate at yOf(upperH): same.
4. Height dimension line: between the plates, a vertical double arrow at x = padL + plotW + 12 (right side) showing d. And labels.
Hmm, padR is 30, might be tight. Let's increase padR to 60 to fit the dimension arrow.
Actually, let's put the dimension arrow at x = padL + plotW - 20 (inside the plot on the right). Or outside. Let's use outside with padR = 56.
5. Oil drop at (cx, yOf(dropH)).
6. Force arrows near the drop.
7. Plate labels: "上极板 y = 5.00 mm (+)" and "下极板 y = 0.00 mm (−)".
Hmm, polarity depends on U sign. If U > 0, upper plate is +, lower is −. If U < 0, reversed. If U = 0, no polarity.
Let's draw the labels on the plates themselves.
Let me write the render function.
```js
function render() {
const ctx = ...;
ctx.clearRect(0, 0, CW, CH);
const padL = 80, padR = 58, padT = 40, padB = 56;
const plotW = CW - padL - padR;
const plotH = CH - padT - padB;
const MAX_MM = 11;
const pxPerMm = plotH / MAX_MM;
const yOf = mm => padT + plotH - mm * pxPerMm;
const cx = padL + plotW / 2;
...
}
```
Wait, padT + plotH = CH - padB. So yOf(0) = CH - padB. And yOf(MAX_MM) = padT. Good.
Now drawing the grid and axis.
Let me write it.
```js
// grid
ctx.strokeStyle = 'rgba(120,160,220,0.10)';
ctx.lineWidth = 1;
for (let mm = 0; mm <= MAX_MM; mm++) {
const y = yOf(mm);
ctx.beginPath();
ctx.moveTo(padL, y);
ctx.lineTo(padL + plotW, y);
ctx.stroke();
}
// axis
const axisX = padL - 30;
ctx.strokeStyle = 'rgba(140,180,240,0.55)';
ctx.beginPath();
ctx.moveTo(axisX, yOf(0));
ctx.lineTo(axisX, yOf(MAX_MM));
ctx.stroke();
ctx.fillStyle = 'rgba(170,200,240,0.75)';
ctx.font = '11px ...';
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
for (let mm = 0; mm <= MAX_MM; mm++) {
const y = yOf(mm);
ctx.beginPath();
ctx.moveTo(axisX - 5, y);
ctx.lineTo(axisX, y);
ctx.stroke();
ctx.fillText(mm.toFixed(0), axisX - 9, y);
}
```
Hmm, but the axis labels need to not collide with the plate labels. Should be fine.
Wait, actually the axis is at x = padL - 30 = 50, and the labels are right-aligned at x = 41. With padL = 80, that leaves room. Good.
Now plates.
```js
function drawPlate(y, label, polarity, color) {
const h = 13;
const g = ctx.createLinearGradient(0, y - h/2, 0, y + h/2);
...
}
```
Let me make the plates look metallic.
Lower plate:
```js
const plateH = 13;
// lower plate at yOf(0), extends downward? or centered?
```
Let's center the plate on the y position. Actually, for the lower plate, the top surface is at y = 0. So the plate body should be below yOf(0). Let's draw it from yOf(0) to yOf(0) + plateH.
For the upper plate, the bottom surface is at y = upperH. So the body should be above: from yOf(upperH) - plateH to yOf(upperH).
Hmm, that's physically right (the gap between the inner surfaces is d). Let's do that.
```js
// lower plate
const lpY = yOf(S.lowerH);
const upY = yOf(S.upperH);
drawPlateRect(padL, lpY, plotW, 13, '#8fa8c8');
drawPlateRect(padL, upY - 13, plotW, 13, '#8fa8c8');
```
Hmm, but then the distance between the inner surfaces is (upY - 13) to lpY, which is not exactly upperH in pixels (it's upperH*pxPerMm - 13). Visually it's fine, but the dimension arrow should go from lpY to upY.
Actually, let's just make the plates thin (10px) and center them on their y positions. Simpler and the dimension arrow from lpY to upY is accurate. But then the "gap" isn't exactly d. It's a schematic; fine.
Hmm, I'll draw them as thin bars centered on their y-coordinates. That makes the geometry consistent with the labeled heights.
Actually no — for the lower plate, if it's centered at y=0, half the plate is below the axis. That's fine visually since there's padB space.
Let's do: plates centered on their heights, thickness 12px. Good.
Now the drop:
```js
const dx = cx, dy = yOf(S.dropH);
const rPx = 11;
const grad = ctx.createRadialGradient(dx - 4, dy - 4, 1, dx, dy, rPx);
grad.addColorStop(0, '#fff8d0');
grad.addColorStop(0.5, '#ffd166');
grad.addColorStop(1, '#c98a1a');
ctx.beginPath();
ctx.arc(dx, dy, rPx, 0, Math.PI*2);
ctx.fillStyle = grad;
ctx.fill();
ctx.strokeStyle = 'rgba(255,240,180,0.9)';
ctx.lineWidth = 1.5;
ctx.stroke();
```
Force arrows: draw from the drop.
```js
const p = physics();
const F_SCALE = 70 / 3.5e-13; // px per Newton...
```
Max force: |Fe| max = 10e * 1000/0.002 = 10*1.602e-19*500000 = 8.01e-13 N. Hmm, with d = 2mm and U = 1000. That's big. Let's use F_SCALE = 60 / 8e-13 = 7.5e13 px/N. Then Fg = 3.69e-14 → 2.8 px. Too small to see.
Hmm. The gravity arrow would be tiny. Let's use a log scale or a fixed reference.
Alternative: normalize by a reference force Fg (weight). Draw the electric force arrow relative to gravity. E.g., gravity arrow = 30 px always, electric arrow = 30 * |Fe|/Fg px, capped at 90 px.
That's more intuitive: shows how many times the electric force is compared to gravity. Let's do that.
- Gravity arrow: 34 px down.
- Electric arrow: 34 * |Fe/Fg| px, capped at 110, up or down depending on sign.
Good.
Positions: electric arrow at x = cx + 26, gravity arrow at x = cx + 52. Hmm, but then they're both to the right. Let's put electric on the left (cx - 26) and gravity on the right (cx + 26). But the drop is at cx, so arrows at cx±26 might overlap the drop (radius 11). Fine.
Hmm, but the plot area — cx is the center, so there's room.
Actually, let's put both arrows to the right of the drop: electric at cx + 30, gravity at cx + 58. And add labels "Fe" and "G". That's cleaner.
Hmm, but the arrow lengths vary, and gravity is always 34. Let's just do it.
Let me draw an arrow function:
```js
function arrow(ctx, x, y0, y1, color, label) {
const dir = Math.sign(y1 - y0) || 1;
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.lineWidth = 2.5;
ctx.beginPath();
ctx.moveTo(x, y0);
ctx.lineTo(x, y1 - dir * 7);
ctx.stroke();
// head
ctx.beginPath();
ctx.moveTo(x, y1);
ctx.lineTo(x - 5, y1 - dir * 8);
ctx.lineTo(x + 5, y1 - dir * 8);
ctx.closePath();
ctx.fill();
if (label) { ... }
}
```
OK.
Now let's think about the "records" list.
```html
实验记录 0
暂无记录,点击"记录数据"保存当前状态
```
Each record item:
```html
#112:00:00
U 300 V
q -5e
d 5.00 mm
h 2.50 mm
Fnet 1.12e-14 N ↑
v 0.65 mm/s ↑
```
Good.
Now let's write the number formatting helper.
```js
function sci(x, digits = 2) {
if (x === 0) return '0';
return x.toExponential(digits).replace('e', '×10^')...
}
```
Hmm, superscript is nicer. Let's just use `x.toExponential(2)` → "1.12e-14". And display as "1.12×10⁻¹⁴". Let's do a simple replacement using unicode superscripts. Meh, let's just use toExponential(2) and render "1.12e-14 N". Simpler and readable.
Actually let's make it nicer: `1.12 × 10⁻¹⁴`. I'll write a helper.
```js
const SUP = {'0':'⁰','1':'¹','2':'²','3':'³','4':'⁴','5':'⁵','6':'⁶','7':'⁷','8':'⁸','9':'⁹','-':'⁻','+':''};
function fmtSci(x, d=2) {
if (!isFinite(x)) return '—';
if (x === 0) return '0';
const s = x.toExponential(d);
const [m, e] = s.split('e');
const exp = e.split('').map(c => SUP[c] || c).join('');
return `${m}×10${exp}`;
}
```
Good.
Now, let's write everything.
One more consideration: the oil drop height slider's max should be S.upperH. Update when upperH changes.
Also, the default drop height 2.5 with upperH 5. Good.
Let me also add a "自动记录" — no, keep it manual.
Let's also handle: when the drop is resting on a plate, the velocity should show 0. Actually, the physics function computes terminal velocity regardless. If the drop is at the boundary and the net force pushes it into the plate, it stays. Let's compute an "effective velocity" for display:
```js
let vEff = p.v;
if (S.dropH <= S.lowerH + 1e-9 && vEff < 0) vEff = 0;
if (S.dropH >= S.upperH - 1e-9 && vEff > 0) vEff = 0;
```
Good.
Now let's write the code.
Also need to handle the voltage slider display and the polarity label.
Let me write the HTML controls:
```html
正电压:上极板为正极
```
etc.
Let me now write out the full code.
```html
密立根油滴实验 · 交互模拟
```
I'll write the whole thing now carefully.
For the layout:
```css
.wrap{max-width:1400px;margin:0 auto;display:grid;grid-template-columns:minmax(0,1fr) 400px;gap:16px;}
@media (max-width:1000px){.wrap{grid-template-columns:1fr;}}
```
Header across the top.
Let me write it.
Now, one thing: I need to make sure the canvas container has a definite height. Using `canvas{display:block;width:100%}` and computing the height from the width.
Let me write the resize function to be called on load and on window resize.
```js
function resizeCanvas(){
const rect = cvWrap.getBoundingClientRect();
const w = Math.max(320, rect.width);
const h = Math.round(Math.min(680, Math.max(430, w * 1.22)));
const dpr = window.devicePixelRatio || 1;
cv.width = Math.round(w*dpr);
cv.height = Math.round(h*dpr);
cv.style.width = w+'px';
cv.style.height = h+'px';
ctx.setTransform(dpr,0,0,dpr,0,0);
CW = w; CH = h;
}
```
Then render.
Alright, writing the full code now.
Let me be careful with the force arrow drawing and labels.
Also, I want to display the plate heights clearly. Let's add labels inside/near the plates:
- Upper plate: text on the plate "上极板 h₂ = 5.00 mm"
- Lower plate: "下极板 h₁ = 0.00 mm"
And a dimension arrow between them on the right side labeled "d = 5.00 mm".
Let me write.
For the dimension line at x = padL + plotW + 22:
- vertical line from yOf(lowerH) to yOf(upperH)
- arrowheads at both ends
- text label rotated? Or horizontal text to the right. padR = 58, so from padL+plotW+22 to CW there's 36 px. Text "d=5.00mm" is too wide. Let's put the label rotated 90°.
Or, put the dimension line inside the plot area on the right: x = padL + plotW - 18. Then the label can be placed next to it... still tight.
Let's just rotate the text -90°.
```js
ctx.save();
ctx.translate(dimX + 16, (yOf(lowerH)+yOf(upperH))/2);
ctx.rotate(-Math.PI/2);
ctx.textAlign='center'; ctx.textBaseline='bottom';
ctx.fillText(`d = ${d.toFixed(2)} mm`, 0, 0);
ctx.restore();
```
Hmm, with padR = 58 and dimX = padL + plotW + 18, the text at dimX+16 rotated would be within padR if the text height is ~14px. Let's set padR = 66.
Actually, rotated text extends along y, and its width along x is the font height (~12px). So dimX + 16 + 6 = padL+plotW+18+22 = padL+plotW+40. Need padR >= 46. OK, padR = 56 is fine.
Alright.
Let me now write out everything properly.
Also I should double check the physics numbers.
MASS = 4/3 * π * (1e-6)³ * 900
(1e-6)³ = 1e-18
4/3 * π = 4.18879
4.18879e-18 * 900 = 3.7699e-15 kg ✓
Fg = 3.7699e-15 * 9.81 = 3.698e-14 N ✓
DRAG_C = 6π * 1.81e-5 * 1e-6 = 6 * 3.14159 * 1.81e-11 = 18.8496 * 1.81e-11 = 3.4118e-10 ✓
Terminal velocity from gravity: 3.698e-14 / 3.4118e-10 = 1.084e-4 m/s = 0.108 mm/s ✓
Default: U=300, d=5mm=0.005m, E=60000 V/m, q=-5e=-8.01e-19 C
Fe = -q*E = 8.01e-19 * 60000 = 4.806e-14 N up ✓
Fnet = 4.806e-14 - 3.698e-14 = 1.108e-14 N up
v = 1.108e-14 / 3.4118e-10 = 3.248e-5 m/s = 0.0325 mm/s
With TIME_SCALE=20: 0.65 mm/s on screen time.
Drop at 2.5mm rises to 5mm (2.5mm) in 3.85 s.
Now, hmm — 3.85 s to cross. That's reasonable.
Let's set TIME_SCALE = 20.
Actually, let me reconsider — maybe make it a bit faster, TIME_SCALE = 25. Meh, 20 is fine.
Now, a concern: with U=1000 and q=-10e, d=2mm:
E = 500000 V/m
Fe = 10*1.602e-19*500000 = 8.01e-13 N
Fnet = 8.01e-13 - 3.7e-14 = 7.64e-13
v = 7.64e-13/3.41e-10 = 2.24e-3 m/s = 2.24 mm/s
× 20 = 44.8 mm/s on screen. Crossing 2mm takes 0.045s. Basically instant.
Hmm, that's too fast. Let's reduce TIME_SCALE to 10. Then it's 22 mm/s, crossing 2mm in 0.09s. Still fast.
Well, the slider ranges are wide. Maybe cap the voltage range to ±600 V. Then at 600V, d=2mm, q=10e: E=300000, Fe = 4.8e-13, Fnet=4.4e-13, v=1.29e-3 m/s = 1.29 mm/s → ×20 = 25.8 mm/s. Crossing 2mm in 0.08s.
Hmm. The dynamic range is inherently large. That's the physics. It's fine — the user can see it move fast.
Actually, let's make TIME_SCALE adaptive? No, that's confusing.
Let's just use TIME_SCALE = 12. Default crossing time: 2.5mm / (0.0325*12) = 2.5/0.39 = 6.4 s. A bit slow but OK. Hmm.
Let's use 20 and accept that high voltages move fast. Actually, I could make the voltage range ±500 and the charge range -8 to +8. Then the max speed is 0.5*8/5 * 1.084e-4... let me compute: v_max = (Fe_max - Fg)/DRAG_C where Fe_max = 8*1.602e-19 * (500/0.002) = 1.2816e-18 * 250000 = 3.204e-13. v = (3.204e-13 - 3.7e-14)/3.41e-10 = 8.3e-4 m/s = 0.83 mm/s → ×20 = 16.6 mm/s. Crossing 2mm in 0.12s. Still fast but acceptable.
Hmm, the issue is d=2mm gives a huge E. Let's set the minimum plate separation to 3mm. Then E_max = 500/0.003 = 166667, Fe_max = 1.2816e-18*166667 = 2.136e-13. v = 5.2e-4 m/s = 0.52 mm/s → ×20 = 10.4 mm/s. Crossing 3mm in 0.29s. OK.
Alright, ranges:
- U: -600 to 600 V, step 5, default 300
- Upper plate height: 3.0 to 10.0 mm, step 0.1, default 5.0
- Charge: -8 to 8 e, step 1, default -5
- Drop height: 0 to upperH
Let's go with that.
Hmm, actually, let's keep U at ±800 for more range. Nah, ±600 is fine.
Let me finalize: U range -600..600, step 5.
Default U = 300, q = -5e, upperH = 5, dropH = 2.5.
OK, writing.
One more: I should add a legend for the force arrows.
Let's put a small legend in the corner of the canvas or below it.
I'll add it as HTML below the canvas.
Let's write the final code.
```js
// ====== 常量 ======
const E_CHARGE = 1.602e-19;
const G_ACC = 9.81;
const ETA = 1.81e-5;
const R_DROP = 1e-6;
const RHO_OIL = 900;
const MASS = (4/3)*Math.PI*Math.pow(R_DROP,3)*RHO_OIL;
const DRAG = 6*Math.PI*ETA*R_DROP;
const TIME_SCALE = 20;
const F_GRAV = MASS*G_ACC;
```
State and physics.
```js
const S = {
U: 300,
upperH: 5.0,
lowerH: 0.0,
dropH: 2.5,
qe: -5,
running: false,
records: []
};
function physics(){
const d = Math.max(0.0001, (S.upperH - S.lowerH)/1000);
const E = S.U / d; // V/m,正电压→场强方向向下
const q = S.qe * E_CHARGE; // C
const Fe = -q * E; // 向上为正
const Fnet = Fe - F_GRAV; // 向上为正
const v = Fnet / DRAG; // m/s,向上为正(终端速度)
return { d, E, q, Fe, Fnet, v };
}
```
Wait, F_GRAV = MASS*G_ACC = 3.698e-14. Fnet = Fe - F_GRAV. ✓
Now the render loop.
Let me write the whole file.
Also: when the drop hits a plate, should we stop the simulation? No, just clamp.
Let's write.
For the record capture, I'll include a snapshot of the physics.
```js
function addRecord(){
const p = physics();
const rec = {
id: S.records.length + 1,
time: new Date().toLocaleTimeString('zh-CN', {hour12:false}),
U: S.U,
qe: S.qe,
upperH: S.upperH,
lowerH: S.lowerH,
dropH: S.dropH,
d: p.d*1000,
E: p.E,
Fe: p.Fe,
Fnet: p.Fnet,
v: p.v*1000 // mm/s
};
S.records.unshift(rec);
renderRecords();
}
```
Use unshift so newest is at the top. Then the id should be a counter.
Let's use a counter.
OK, writing the final code now.
For the records rendering:
```js
function renderRecords(){
const list = document.getElementById('recList');
if (!S.records.length){
list.innerHTML = '
`).join('');
}
```
Hmm, the direction indicator for Fnet would be nice.
Let me add a direction arrow character.
OK, writing the final answer now.
Let me also double check: `S.records.length + 1` for id — if we never delete, that works. But let's use a separate counter to be safe.
Now writing everything.
One more detail: the "oil drop height" slider needs its max updated when upperH changes:
```js
rngUpper.addEventListener('input', () => {
S.upperH = parseFloat(rngUpper.value);
if (S.dropH > S.upperH) S.dropH = S.upperH;
rngDrop.max = S.upperH;
rngDrop.value = S.dropH;
updateReadouts();
});
```
And rngDrop's max is S.upperH, so `rngDrop.max = S.upperH`.
Let me write it.
Also the reset button should restore defaults.
Let me write the final code.
I'll make sure the code is complete and runnable.
Let me write the render function fully:
```js
function render(){
if (!ctx) return;
const padL = 84, padR = 62, padT = 44, padB = 58;
const plotW = Math.max(60, CW - padL - padR);
const plotH = Math.max(60, CH - padT - padB);
const MAX_MM = 11;
const pxPerMm = plotH / MAX_MM;
const yOf = mm => padT + plotH - mm*pxPerMm;
const cx = padL + plotW/2;
ctx.clearRect(0,0,CW,CH);
// 背景
const bg = ctx.createLinearGradient(0,0,0,CH);
bg.addColorStop(0,'rgba(20,36,62,0.55)');
bg.addColorStop(1,'rgba(10,18,32,0.55)');
ctx.fillStyle = bg;
roundRect(ctx, padL-8, padT-10, plotW+16, plotH+20, 12);
ctx.fill();
// 网格
ctx.lineWidth = 1;
ctx.strokeStyle = 'rgba(110,160,230,0.12)';
for (let mm=0; mm<=MAX_MM; mm++){
const y = yOf(mm);
ctx.beginPath(); ctx.moveTo(padL, y); ctx.lineTo(padL+plotW, y); ctx.stroke();
}
// 纵轴
const axisX = padL - 26;
ctx.strokeStyle = 'rgba(140,180,240,0.5)';
ctx.beginPath(); ctx.moveTo(axisX, yOf(0)); ctx.lineTo(axisX, yOf(MAX_MM)); ctx.stroke();
ctx.fillStyle = 'rgba(160,195,240,0.8)';
ctx.font = '11px ui-monospace, Consolas, monospace';
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
for (let mm=0; mm<=MAX_MM; mm++){
const y = yOf(mm);
ctx.beginPath(); ctx.moveTo(axisX-5, y); ctx.lineTo(axisX, y); ctx.stroke();
if (mm % 1 === 0) ctx.fillText(mm.toString(), axisX-9, y);
}
ctx.save();
ctx.translate(axisX-40, yOf(MAX_MM/2));
ctx.rotate(-Math.PI/2);
ctx.textAlign='center'; ctx.textBaseline='middle';
ctx.fillStyle='rgba(160,195,240,0.7)';
ctx.fillText('高度 / mm', 0, 0);
ctx.restore();
...
}
```
Hmm, the axis label at axisX-40 = padL - 66 = 18. That's fine within the canvas.
Wait, padL = 84, axisX = 58, axisX - 40 = 18. OK.
But the tick labels are right-aligned at axisX-9 = 49, so they extend leftward from 49. For "10" that's ~13px wide, so from 36 to 49. And the axis label is at x=18. OK, no overlap.
Good.
Now plates.
```js
const plateThick = 12;
function drawPlate(yc, label, sub, polarity){
const x0 = padL, x1 = padL + plotW;
const g = ctx.createLinearGradient(0, yc - plateThick/2, 0, yc + plateThick/2);
g.addColorStop(0, '#b9cde8');
g.addColorStop(0.45, '#7f9bc0');
g.addColorStop(0.55, '#5f7ea6');
g.addColorStop(1, '#8ea9cc');
ctx.fillStyle = g;
roundRect(ctx, x0, yc - plateThick/2, plotW, plateThick, 4);
ctx.fill();
ctx.strokeStyle = 'rgba(200,225,255,0.45)';
ctx.lineWidth = 1;
ctx.stroke();
...
}
```
Hmm, labels on the plates. Let's put the label text above/below the plate.
For the lower plate (at y=0), the label should go below.
For the upper plate, the label should go above.
Actually, since the plates can be close together, let's put the lower plate label below it and the upper plate label above it.
```js
ctx.font = '12px ...';
ctx.fillStyle = '#cfe0f7';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.fillText(label, padL + 10, yc + (isLower ? 20 : -20));
```
Hmm, but the plate thickness is 12, so ±20 puts the text outside. Good.
Wait, for the lower plate at y = yOf(0) = padT + plotH (bottom of the plot area), the label at yc+20 would be at padT+plotH+20, and padB = 58, so there's room. Good.
For the upper plate at yOf(upperH), if upperH = 10 and MAX_MM = 11, then yOf(10) = padT + plotH - 10*pxPerMm = padT + plotH/11 ≈ padT + 45. The label at yc-20 = padT+25. That's within the plot area (padT=44)... wait, padT+25 < padT, so it's above the plot area but still within the canvas (padT = 44 > 25). Hmm, y=25 is above padT=44, so it's in the top margin. That's fine, still visible.
Actually wait, I need to double check. yOf(10) = padT + plotH - 10*(plotH/11) = padT + plotH/11. If plotH = 500, then padT + 45.5 = 44 + 45.5 = 89.5. Label at 89.5 - 20 = 69.5. That's below padT=44. Fine.
If plotH = 300, yOf(10) = 44 + 27 = 71, label at 51. Still > 44. OK fine.
Alright.
Now the polarity indicators: "+" and "−" signs on the plates.
If U > 0: upper is +, lower is −.
If U < 0: upper is −, lower is +.
If U == 0: no signs.
Draw them at the right end of the plates.
OK.
Now the dimension line between the plates.
```js
const dimX = padL + plotW + 20;
const y1 = yOf(S.lowerH), y2 = yOf(S.upperH);
ctx.strokeStyle = 'rgba(120,220,180,0.85)';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(dimX, y1); ctx.lineTo(dimX, y2);
ctx.stroke();
// arrowheads
drawArrowHead(dimX, y1, 'down');
drawArrowHead(dimX, y2, 'up');
// ticks
ctx.beginPath();
ctx.moveTo(dimX-6, y1); ctx.lineTo(dimX+6, y1);
ctx.moveTo(dimX-6, y2); ctx.lineTo(dimX+6, y2);
ctx.stroke();
// label
ctx.save();
ctx.translate(dimX+18, (y1+y2)/2);
ctx.rotate(-Math.PI/2);
ctx.textAlign='center'; ctx.textBaseline='bottom';
ctx.fillStyle = '#7fe3b8';
ctx.font = 'bold 12px ui-monospace, monospace';
ctx.fillText(`d = ${(S.upperH-S.lowerH).toFixed(2)} mm`, 0, 0);
ctx.restore();
```
Hmm, `textBaseline='bottom'` with rotation — the text is drawn rotated -90°, so "bottom" is to the right. Let me think: after rotating -90°, the local x-axis points up (screen), local y-axis points right (screen). So text drawn along local +x goes up on screen. textBaseline 'bottom' means the text sits above the local baseline, which in screen coords is to the... hmm.
Local y+ = screen x+. So textBaseline='bottom' places the text at local y < 0, i.e., screen x < translateX. So the text would be to the LEFT of dimX+18. Hmm, that would overlap the dimension line.
Let's use textBaseline='top' so the text is at local y>0 → screen x > translateX. Wait, no: textBaseline='top' means the top of the text is at the local y position, so the text extends in local +y → screen +x. So the text extends to the right of dimX+18. Good.
Hmm, but then the text would be from dimX+18 to dimX+18+12 = dimX+30 = padL+plotW+50. And padR = 62, so the plot right edge is at padL+plotW, and the canvas right edge is at padL+plotW+62. So dimX+30 is within bounds.
Actually wait, let me redo: I want the label to the right of the dimension line. Let me just not rotate and use small font. "d=5.00mm" at 11px is about 55px wide. padR = 62. dimX = padL+plotW+20. Text from dimX+4 to dimX+59 = padL+plotW+79. That exceeds padR=62.
So rotation is better. Let's rotate.
Actually, alternatively, put the d label as part of the readout panel and just show "d" with the arrow. Or put the label horizontally centered in the gap between the plates, offset to the right inside the plot.
Hmm, let's just do the rotated label. It's clean.
Let me set padR = 70 to be safe.
OK.
Now the drop and force arrows.
```js
const p = physics();
const dy = yOf(S.dropH);
// 高度参考虚线
ctx.setLineDash([5,5]);
ctx.strokeStyle = 'rgba(255,209,102,0.35)';
ctx.beginPath();
ctx.moveTo(padL, dy); ctx.lineTo(padL+plotW, dy);
ctx.stroke();
ctx.setLineDash([]);
```
Then the drop.
Then force arrows.
```js
const Fg = F_GRAV;
const arrowScale = 34 / Fg; // 重力箭头固定 34px
const fePx = Math.min(120, Math.abs(p.Fe) * arrowScale);
const fgPx = 34;
```
Draw at x = cx + 30 (Fe) and cx + 58 (Fg)? Hmm, cx + 58 might be close to the right edge. cx = padL + plotW/2. padL+plotW/2+58 vs padL+plotW → plotW/2 + 58 vs plotW → need plotW > 116. Should be fine.
Let's use cx + 34 and cx + 62.
Hmm, actually let me place them to the right of the drop but ensure they don't collide with the dimension line at padL+plotW+20.
cx + 62 = padL + plotW/2 + 62. For plotW = 500, that's padL + 312, well within.
OK good.
Fe arrow: from (xFe, dy) to (xFe, dy - fePx) if Fe > 0 (up), or to (xFe, dy + fePx) if Fe < 0.
Fg arrow: always down: from (xFg, dy) to (xFg, dy + fgPx).
Labels: "Fe" and "G" at the arrow tips.
Let's draw.
Hmm, one issue: if the drop is near the bottom, the Fg arrow goes below the plot. That's OK, it's still on the canvas (padB=58).
If the drop is near the top, the Fe arrow goes above. padT=44. Might clip. Let's clamp the drop's drawing... nah, it's fine.
Let me now finalize and write.
Also I want a subtle glow on the drop.
OK, writing the final code.
Let me write the update loop:
```js
let lastT = performance.now();
function tick(now){
const dtReal = Math.min(0.05, (now - lastT)/1000);
lastT = now;
if (S.running){
const p = physics();
let v = p.v; // m/s up
// 边界
if (S.dropH <= S.lowerH + 1e-9 && v < 0) v = 0;
if (S.dropH >= S.upperH - 1e-9 && v > 0) v = 0;
S.dropH += v * 1000 * dtReal * TIME_SCALE;
S.dropH = Math.max(S.lowerH, Math.min(S.upperH, S.dropH));
}
syncControls();
render();
requestAnimationFrame(tick);
}
```
Hmm, `syncControls` sets the slider value. If the user is dragging the slider, this would fight. But since we set the slider value to S.dropH, and the user's input sets S.dropH, it should be consistent. Actually, if the user drags while running, the input event fires, sets S.dropH, then the next frame moves it slightly and sets the slider value. Should be fine.
But there's a subtlety: the slider has step 0.01, so setting value to 2.5345 rounds to 2.53. Fine.
Actually, to avoid janky feedback, let me only update the slider value if the drop is moving (i.e., S.running) and the user isn't actively dragging. Let's track `dragging` via pointerdown/up on the slider. Simpler: just always sync. It's fine.
Hmm, actually there IS a problem: if the user drags the slider, the input event sets S.dropH. Then in the same frame, syncControls sets the slider value from S.dropH — same value, no issue. OK fine.
Let me write `updateUI()` that updates all the readouts and the slider positions.
Alright, let me write it all out.
Final code:
Actually, let me reconsider the "record" feature — maybe auto-record when the user clicks a button. Yes, manual.
Let me write.
I also want to show the number of electrons: q = n*e where n = S.qe. So "电荷量 q = -5e = -8.01×10⁻¹⁹ C".
OK.
Writing now.
Let me make sure `roundRect` is defined:
```js
function roundRect(ctx, x, y, w, h, r){
const rr = Math.min(r, w/2, h/2);
ctx.beginPath();
ctx.moveTo(x+rr, y);
ctx.arcTo(x+w, y, x+w, y+h, rr);
ctx.arcTo(x+w, y+h, x, y+h, rr);
ctx.arcTo(x, y+h, x, y, rr);
ctx.arcTo(x, y, x+w, y, rr);
ctx.closePath();
}
```
Good.
Now, writing the complete file.
Let me also handle the "开始/暂停" button text.
Final structure of the HTML:
```html
密立根油滴实验 · 交互模拟
调节电压、极板高度与油滴电荷,观察油滴在重力与电场力作用下的运动
...
...
```
Hmm, let me restructure: the header spans full width, then a 2-column layout.
```css
.wrap{max-width:1440px;margin:0 auto;}
.hero{...}
.layout{display:grid;grid-template-columns:minmax(0,1fr) 420px;gap:16px;margin-top:16px;}
@media(max-width:1060px){.layout{grid-template-columns:1fr;}}
```
OK. Writing.
For the readout, I'll use a grid of stat items.
Let me write it now, final.
I need to be careful with the `physics()` function being called in render — it's cheap.
Let me write out the complete code.
Also: the drop height slider max needs to be set initially.
Alright, here's the final code.
One more thought on the force arrow scale: with Fg = 3.7e-14 and Fe potentially 0, the Fe arrow would be 0 length. Handle that (skip drawing).
Also, when |Fe| is huge, cap at 120px.
Let me write.
I'll now produce the final answer with the complete HTML file and a brief explanation.
Let me write the CSS carefully for a polished look.
```css
.card{
background: linear-gradient(180deg, rgba(24,40,68,.92), rgba(15,26,46,.92));
border: 1px solid rgba(110,160,230,.18);
border-radius: 16px;
box-shadow: 0 12px 34px rgba(0,0,0,.35), inset 0 1px 0 rgba(255,255,255,.05);
}
```
Controls styling:
```css
.ctrl{margin-bottom:16px}
.ctrl label{display:flex;justify-content:space-between;align-items:baseline;font-size:13px;color:var(--muted);margin-bottom:8px;}
.ctrl output{font-family:ui-monospace,monospace;font-size:14px;color:var(--accent);font-weight:600;}
input[type=range]{ -webkit-appearance:none; width:100%; height:6px; border-radius:6px; background:linear-gradient(90deg,#2b4670,#3a5f92); outline:none;}
input[type=range]::-webkit-slider-thumb{ -webkit-appearance:none; width:18px;height:18px;border-radius:50%; background:radial-gradient(circle at 35% 30%, #9fd0ff, #3f8fe0); border:2px solid #0b1729; box-shadow:0 0 10px rgba(77,163,255,.7); cursor:pointer;}
input[type=range]::-moz-range-thumb{...}
```
OK.
Let me write the whole thing.
For the buttons:
```css
.btn{
border:1px solid rgba(110,160,230,.3);
background:linear-gradient(180deg,#22406b,#172c4b);
color:#dbe8fb; padding:10px 14px; border-radius:10px; cursor:pointer;
font-size:13px; font-weight:600; transition:.18s;
}
.btn:hover{background:linear-gradient(180deg,#2b5083,#1d3659); border-color:rgba(120,180,255,.55);}
.btn.primary{background:linear-gradient(180deg,#2f7fd6,#1f5ea8);border-color:#4da3ff;color:#fff;}
.btn.danger{...}
```
OK. Let me finalize.
Writing the answer now. I'll keep the explanation brief and focus on the code.
Let me carefully write the JS render function once more to make sure everything is defined.
Actually one thing: in `render()`, I use `S.lowerH` which is always 0. Fine.
Let me write it.
Final code:
```html
密立根油滴实验 · 交互模拟
密立根油滴实验 · 交互模拟
调节电场电压、极板高度与油滴电荷,实时观察油滴在重力与电场力作用下的运动
下极板高度固定为 0.00 mm
油滴电场力 Fe重力 G
```
Now, the readout grid.
```html
```
I'll fill it with innerHTML in JS.
```js
function updateReadout(){
const p = physics();
const items = [
['上极板高度', S.upperH.toFixed(2)+' mm'],
['下极板高度', S.lowerH.toFixed(2)+' mm'],
['极板间距 d', (S.upperH-S.lowerH).toFixed(2)+' mm'],
['电场强度 E', (p.E/1000).toFixed(1)+' kV/m'],
['油滴高度 h', S.dropH.toFixed(2)+' mm'],
['油滴电荷 q', (S.qe>0?'+':'')+S.qe+'e'],
['重力 G', fmtSci(F_GRAV)+' N'],
['电场力 Fₑ', fmtSci(p.Fe)+' N'],
['合力 Fnet', fmtSci(p.Fnet)+' N '+(p.Fnet>0?'↑':p.Fnet<0?'↓':'—')],
['运动速度 v', (p.v*1000).toFixed(3)+' mm/s'],
];
...
}
```
Hmm, `p.v*1000` gives mm/s. With v = 3.25e-5 m/s → 0.0325 mm/s. Good.
But the displayed speed is the "simulation" speed, not real-time. Let's label it "终端速度 v(实时×20)". Or just show the actual terminal velocity in mm/s and note that the animation is sped up.
Let's label: "终端速度 v" and add a note "动画已加速 20×".
OK.
Let me finalize the readout rendering:
```js
readout.innerHTML = items.map(([k,v]) => `
${k}${v}
`).join('');
```
Good.
Now writing everything for real.
Let me double-check the fmtSci function handles negative exponents:
"1.12e-14" → split('e') → ["1.12", "-14"] → exp = "⁻¹⁴" → "1.12×10⁻¹⁴".
Now the code. Let me write it out.
Also need to make sure `physics()` is called before `S` is defined — no, it's called at runtime.
Let me write the final file.
Regarding the drop radius display: I should mention r = 1.0 μm in the panel.
OK, writing.
I'll also add a small "reset" for the drop height.
Final answer below.
Let me also double check the arrow drawing function.
```js
function drawArrow(ctx, x, y0, y1, color, label, labelSide){
const dir = Math.sign(y1 - y0);
if (dir === 0) return;
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.lineWidth = 2.5;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(x, y0);
ctx.lineTo(x, y1 - dir*8);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y1);
ctx.lineTo(x - 5.5, y1 - dir*9);
ctx.lineTo(x + 5.5, y1 - dir*9);
ctx.closePath();
ctx.fill();
if (label){
ctx.font = 'bold 11px ui-monospace, monospace';
ctx.textAlign = 'center';
ctx.textBaseline = dir > 0 ? 'bottom' : 'top';
ctx.fillText(label, x, y1 + (dir > 0 ? 6 : -6));
}
}
```
Hmm, if the arrow points down (dir = 1), the tip is at y1 (below y0). The label should be below the tip: baseline 'top' at y1+6. Let me fix:
```js
ctx.textBaseline = dir > 0 ? 'top' : 'bottom';
ctx.fillText(label, x, y1 + dir*6);
```
Wait, if dir > 0 (pointing down), textBaseline='top' and y = y1 + 6. Good.
If dir < 0 (pointing up), textBaseline='bottom' and y = y1 - 6. Good.
So `ctx.fillText(label, x, y1 + dir*6)` with `textBaseline = dir > 0 ? 'top' : 'bottom'`. Yes.
Hmm, for dir < 0: y = y1 - 6, baseline bottom → text is above y1-6. Good.
OK.
Now writing.
For the gravity arrow, dir is always +1 (down). For the electric arrow, dir depends on the sign of Fe.
Let me write the final code now.
Also, the drop's vertical position: the arrow origin should be at the drop center.
Alright.
One last check on the layout: `.stage` contains the canvas wrapper, legend, and readout. The canvas wrapper needs `width: 100%`.
Let me finalize.
I'm going to write it now.
Also: `S.qe` is an integer from -8 to 8. If qe = 0, there's no electric force.
Let me write.
Oh wait, one issue with `physics()`: if `S.upperH === S.lowerH`, d = 0 → division by zero. But the minimum upperH is 3.0, so d >= 3. Fine. I still guard with Math.max.
OK writing the final answer.
### assistant · answer
This is an interactive Millikan oil drop experiment simulation webpage. You can adjust voltage, plate height, and oil drop charge, then watch the drop move in real time.
```html
密立根油滴实验 · 交互模拟
密立根油滴实验 · 交互模拟
调节电场电压、极板高度与油滴电荷,实时观察油滴在重力与电场力作用下的运动
下极板高度固定为 0.00 mm
油滴(r = 1.0 μm,ρ = 900 kg/m³)电场力 Fe重力 G动画已加速 20×
```
### How the Simulation and Controls Work
Here's a quick tour of the main controls and what they do.
- **Adjustable parameters:** Use the sliders to change voltage, upper plate height, charge, and oil drop height. The lower plate stays at 0 mm.
- **Real-time motion:** The drop responds to the net force from gravity and the electric field. If the electric force overcomes gravity, the drop rises; otherwise, it falls. Motion stops when it hits either plate.
- **Instant readouts:** The panel below the canvas shows live values for electric field, forces, and terminal velocity. The drop itself also shows its charge sign.
- **Record keeping:** Click the record button to save a snapshot of the current settings and results. Records appear in a scrollable list on the right, showing key values for each trial.
---
**Optimization Tip:** You can adjust the constants at the top of the script — such as `R_DROP`, `RHO_OIL`, `TIME_SCALE`, and slider ranges — to change the oil drop's physical properties or animation speed. For example, increasing `TIME_SCALE` makes the motion faster.