加载应用…
云澜 Clyune Clyune Component Gallery · 中文

Rotating Cube · How it works & code

Base Scene, Lighting, and Wireframe

Runtime logic

Visiting `/threejs/cube`, DemoHost lazy-loads `demos/cube.js` (registry `mod: 'cube'`) and calls `mountCube(host, { variant: 'cube' })`. `createThreeStage` sets up WebGLRenderer, Scene, PerspectiveCamera and OrbitControls, plus the info panel. The module registers its per-frame callback with `S.onFrame`. Every `requestAnimationFrame`: read controls, advance a speed-scaled clock (dt ≤ 50 ms), run the frame callback; returned readouts go to the info panel. Changing parameters: colour/speed/size apply live; structural ones remount; leaving the page cancels rAF, removes listeners and frees resources.

Environment

Canvas 2D: 2D canvas drawing; WebGL (three.js): WebGL through three.js WebGLRenderer; requestAnimationFrame: Display-synced animation loop; ResizeObserver: Canvas follows container size; Pointer Events: Unified mouse/touch/pen events; devicePixelRatio: Crisp HiDPI rendering (capped at 2×) · react 18.3.1, react-router-dom 6.30.6, vite 5.4.21, three 0.170.0

Dependencies

three 0.170.0, three/addons/controls/OrbitControls.js 0.170.0, react 18.3.1

Imported APIs

createThreeStage — Shared three.js stage: WebGLRenderer, scene, perspective camera, OrbitControls, auto framing and render loop; addLights — Adds ambient + key + fill lights; THREE — three.js namespace; fmt — Number formatting (fixed decimals); deg — Radians → degrees text; F — Formula block HTML; S.onFrame — Registers a per-frame callback; its return value feeds the info panel; THREE.Mesh — Mesh (geometry + material); THREE.BoxGeometry — Box geometry; THREE.MeshStandardMaterial — PBR standard material; THREE.LineSegments — Line segments; THREE.EdgesGeometry — Extracts edges of a geometry; THREE.LineBasicMaterial — Basic line material; THREE.GridHelper — Grid helper

Source code

frontend/src/demos/cube.js: cube.js (L1-L48)

Code walkthrough

L4-10: `PARAMS_SPEC` (constant/table). L11-27: `DOC` (constant/table). L29-48: `mountCube` (function); creates three.js objects `Mesh`, `BoxGeometry`, `MeshStandardMaterial`, `LineSegments`, `EdgesGeometry`, `LineBasicMaterial` …; returns readouts `rx`, `ry`, `wx`, `wy`, `k`, `a` to the info panel.

Principles

θ(t) = θ₀ + ω · t ωx = 0.6 · k, ωy = 0.9 · k( Illustration) V = a³,S = 6a² A basic one Three.js Scenes: Scene Scene Release the object Camera Camera It's decided where to look Renderer Renderer Each frame paints the picture on the canvas. Every frame of diamonds X, Y The axes Boards turn a little bit, and the angles follow time Speed Increase ,This is it“Rotation of Oprah”。灯光让每个面明暗不同,你才看得出它是立体的。

Open the interactive demo · GitHub