← All components Next component3D Slider→
Navigation · Indicator
Scroll Compass
A chrome compass pinned to a corner: the needle tracks reading progress and the dial leans with scroll speed.
Scroll the page — the needle tracks your reading progress
<ScrollCompass3D />Live
Scroll the page to turn the needle
Customize
Needle#a78bfa
Dial#18181b
Installation
Use it in your project
Or skip the copy-paste
One command: writes the file and installs the dependencies.
$ npx deepui-cli add scroll-compass
01
Install
The 3D packages this component is built on.
$ npm install three @react-three/fiber @react-three/drei && npm install -D @types/three
02
Add the component
One self-contained file: create components/ScrollCompass3D.tsx and paste it in.
components/ScrollCompass3D.tsx
1"use client";23import {4 memo,5 useEffect,6 useMemo,7 useRef,8 useState,9 type CSSProperties,10 type ReactNode,11 type RefObject,12} from "react";13import * as THREE from "three";14import { Canvas, useFrame, type CanvasProps } from "@react-three/fiber";15import { Environment, Lightformer } from "@react-three/drei";1617/**18 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep19 * their own tailored scenes).20 *21 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its22 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):23 *24 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }25 *26 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,27 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are28 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.29 */3031/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */32export type TiltAxis = "both" | "x-only" | "y-only" | "none";3334/** 1. Cursor: how the pointer pulls, pushes and drags the object. */35interface CursorProps {36 /** Reach of the pointer's influence, in the component's own space: CSS pixels for pixel-laid-out widgets, world units for 3D scenes (each component says which). Default 220 (px). */37 cursorRadius?: number;38 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */39 cursorForce?: number;40 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */41 magneticStrength?: number;42 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */43 cursorDamping?: number;44}4546/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */47interface TiltProps {48 /** Largest lean towards the pointer, in degrees. Default 15. */49 maxTiltAngle?: number;50 /** Axes that follow the pointer. Default "both". */51 tiltAxis?: TiltAxis;52 /** Lean away from the pointer instead of towards it. Default false. */53 invertTilt?: boolean;54 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */55 parallaxOffset?: number;56}5758/** 3. Text and 3D typography, for components that draw a label. */59interface Text3DProps {60 /** The label drawn by the component. */61 text?: string;62 /** Scale of the lettering. Default 1. */63 fontSize?: number;64 /** Extrusion depth of 3D letters. Default 0.2. */65 textDepth?: number;66 /** Bevelled, light-catching edges on 3D letters. Default true. */67 bevelEnabled?: boolean;68 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */69 fontUrl?: string;70}7172/** 4. Rendering, materials and glow. */73interface MaterialProps {74 /** Main color of the object. Default "#6366f1". */75 primaryColor?: string;76 /** Color of the glow. Default "#00f0ff". */77 emissiveColor?: string;78 /** Strength of the glow, 0 (none) to 3. Default 1. */79 emissiveIntensity?: number;80 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */81 roughness?: number;82 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */83 metalness?: number;84 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */85 transmission?: number;86 /** Technical wireframe rendering. Default false. */87 wireframe?: boolean;88}8990/** 5. Particles, idle motion and shader animation. */91interface MotionProps {92 /** Number of instanced elements. Default depends on the component. */93 particleCount?: number;94 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */95 autoRotateSpeed?: number;96 /** Pulses or ripples per second. Default 1. */97 pulseRate?: number;98 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */99 displacementScale?: number;100}101102/** 6. Environment and camera. */103interface EnvironmentProps {104 /** Camera field of view, in degrees. Default depends on the component. */105 cameraFov?: number;106 /** Color of the depth fog. Default "#0a0a0a". */107 fogColor?: string;108 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */109 fogDensity?: number;110}111112/** 7. Performance and accessibility. */113interface PerformanceProps {114 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */115 lowPowerMode?: boolean;116 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */117 respectReducedMotion?: boolean;118 /** Stop the render loop while the component is scrolled out of view. Default true. */119 pauseWhenOffscreen?: boolean;120}121122/** Every group at once. Components extend only the groups they apply (see the top of this file). */123interface Base3DComponentProps124 extends CursorProps,125 TiltProps,126 Text3DProps,127 MaterialProps,128 MotionProps,129 EnvironmentProps,130 PerformanceProps {}131132type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;133134/** The values a prop takes when it is left out. A component may override one, and then documents it. */135const DEFAULT_3D_PROPS: Defaults = {136 cursorRadius: 220,137 cursorForce: 1,138 magneticStrength: 0,139 cursorDamping: 0.1,140 maxTiltAngle: 15,141 tiltAxis: "both",142 invertTilt: false,143 parallaxOffset: 1,144 fontSize: 1,145 textDepth: 0.2,146 bevelEnabled: true,147 primaryColor: "#6366f1",148 emissiveColor: "#00f0ff",149 emissiveIntensity: 1,150 roughness: 0.3,151 metalness: 0.5,152 transmission: 0,153 wireframe: false,154 autoRotateSpeed: 0,155 pulseRate: 1,156 displacementScale: 1,157 fogColor: "#0a0a0a",158 fogDensity: 0,159 lowPowerMode: false,160 respectReducedMotion: true,161 pauseWhenOffscreen: true,162};163164/** Inline widget: fills its positioned parent and receives pointer events. */165const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };166167/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */168const OVERLAY_STYLE: CSSProperties = {169 position: "fixed",170 top: 0,171 left: 0,172 width: "100%",173 height: "100%",174 pointerEvents: "none",175 zIndex: 9999,176};177178interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {179 children: ReactNode;180 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */181 overlay?: boolean;182}183184/**185 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel186 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.187 */188function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {189 const containerRef = useRef<HTMLDivElement>(null);190 // In view at first: the first frame is always drawn before the loop can be paused191 const [inView, setInView] = useState(true);192 useEffect(() => {193 const el = containerRef.current;194 if (!el || !pauseWhenOffscreen) return undefined;195 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));196 observer.observe(el);197 return () => observer.disconnect();198 }, [pauseWhenOffscreen]);199 return (200 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">201 <Canvas202 dpr={lowPowerMode ? 1 : dpr}203 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}204 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}205 style={overlay ? { pointerEvents: "none" } : undefined}206 {...canvasProps}207 >208 {children}209 </Canvas>210 </div>211 );212}213214interface Spring {215 value: number;216 velocity: number;217}218219/** Damped spring step: overshoots a little, then settles. */220function stepSpring(spring: Spring, target: number, stiffness: number, damping: number, dt: number) {221 spring.velocity += (target - spring.value) * stiffness * dt;222 spring.velocity *= Math.exp(-damping * dt);223 spring.value += spring.velocity * dt;224 return spring.value;225}226227export interface ScrollCompassProps extends Pick<MaterialProps, "emissiveColor" | "primaryColor">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {228 /** Needle tip and progress arc. */229 emissiveColor?: string;230 /** @deprecated Use `emissiveColor`. */231 accentColor?: string;232 /** Dial color. */233 primaryColor?: string;234 /** @deprecated Use `primaryColor`. */235 baseColor?: string;236 /** 0–1: how much the needle lags and overshoots (higher = smoother, looser). Default 0.5. */237 smoothness?: number;238 /** Size of the widget, in CSS pixels. Default 112. */239 size?: number;240 /** Corner it is pinned to. Default "bottom-right". */241 corner?: "bottom-right" | "bottom-left" | "top-right" | "top-left";242 /** Pinned to the viewport (true) or to the corner of its positioned parent (false). Default true. */243 fixed?: boolean;244}245246const TICKS = 24;247248const arcFragment = /* glsl */ `249uniform float uProgress;250uniform vec3 uColor;251varying vec2 vUv;252void main() {253 // Angle around the dial, clockwise from 12 o'clock, 0..1254 vec2 p = vUv - 0.5;255 float a = fract(atan(p.x, p.y) / 6.2831853 + 1.0);256 float filled = step(a, uProgress);257 float r = length(p) * 2.0;258 float band = smoothstep(0.78, 0.8, r) * (1.0 - smoothstep(0.9, 0.92, r));259 vec3 color = mix(vec3(0.16), uColor * 1.4, filled);260 gl_FragColor = vec4(color, band * mix(0.5, 1.0, filled));261 #include <colorspace_fragment>262}263`;264265interface ScrollState {266 progress: number;267 velocity: number;268}269270const Compass = memo(function Compass({ accentColor, baseColor, smoothness, scroll }: Required<Omit<ScrollCompassProps, "emissiveColor" | "primaryColor" | "pauseWhenOffscreen" | "lowPowerMode" | "size" | "corner" | "fixed">> & { scroll: RefObject<ScrollState> }) {271 const dialRef = useRef<THREE.Group>(null);272 const needleRef = useRef<THREE.Group>(null);273 const needle = useRef<Spring>({ value: 0, velocity: 0 });274 const tilt = useRef({ x: 0, y: 0 });275276 const geometries = useMemo(() => {277 const disc = new THREE.CylinderGeometry(1, 1, 0.16, 64);278 disc.rotateX(Math.PI / 2);279 return {280 disc,281 bezel: new THREE.TorusGeometry(1.02, 0.06, 16, 96),282 arc: new THREE.PlaneGeometry(2.1, 2.1),283 tick: new THREE.BoxGeometry(0.03, 0.11, 0.04),284 tip: new THREE.ConeGeometry(0.11, 0.62, 24),285 tail: new THREE.ConeGeometry(0.09, 0.42, 24),286 cap: new THREE.SphereGeometry(0.11, 24, 24),287 };288 }, []);289 const materials = useMemo(290 () => ({291 dial: new THREE.MeshPhysicalMaterial({ metalness: 0.6, roughness: 0.35, clearcoat: 1 }),292 chrome: new THREE.MeshStandardMaterial({ color: "#e4e4e7", metalness: 1, roughness: 0.15 }),293 tip: new THREE.MeshStandardMaterial({ metalness: 0.3, roughness: 0.3, emissiveIntensity: 0.6 }),294 arc: new THREE.ShaderMaterial({295 uniforms: { uProgress: { value: 0 }, uColor: { value: new THREE.Color() } },296 vertexShader: /* glsl */ `297 varying vec2 vUv;298 void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }299 `,300 fragmentShader: arcFragment,301 transparent: true,302 depthWrite: false,303 }),304 }),305 []306 );307308 useEffect(() => {309 materials.dial.color.set(baseColor);310 materials.tip.color.set(accentColor);311 materials.tip.emissive.set(accentColor);312 (materials.arc.uniforms.uColor.value as THREE.Color).set(accentColor);313 }, [materials, accentColor, baseColor]);314 useEffect(315 () => () => {316 Object.values(geometries).forEach((g) => g.dispose());317 Object.values(materials).forEach((m) => m.dispose());318 },319 [geometries, materials]320 );321322 // Tick marks around the dial: one instanced mesh323 const ticks = useMemo(() => {324 const mesh = new THREE.InstancedMesh(geometries.tick, materials.chrome, TICKS);325 const m = new THREE.Matrix4();326 const q = new THREE.Quaternion();327 const z = new THREE.Vector3(0, 0, 1);328 for (let i = 0; i < TICKS; i++) {329 const a = (i / TICKS) * Math.PI * 2;330 const long = i % 6 === 0 ? 1.6 : 1;331 q.setFromAxisAngle(z, -a);332 m.compose(new THREE.Vector3(Math.sin(a) * 0.68, Math.cos(a) * 0.68, 0.1), q, new THREE.Vector3(1, long, 1));333 mesh.setMatrixAt(i, m);334 }335 return mesh;336 }, [geometries, materials]);337 useEffect(() => () => ticks.dispose(), [ticks]);338339 useFrame((_, delta) => {340 const dt = Math.min(delta, 1 / 30);341 const s = scroll.current;342 // The needle follows reading progress (one full turn = the whole page) on a spring: the higher the343 // smoothness, the softer the spring and the bigger the overshoot344 const k = THREE.MathUtils.lerp(260, 40, smoothness);345 const damping = THREE.MathUtils.lerp(26, 7, smoothness);346 stepSpring(needle.current, -s.progress * Math.PI * 2, k, damping, dt);347 if (needleRef.current) needleRef.current.rotation.z = needle.current.value;348 materials.arc.uniforms.uProgress.value = THREE.MathUtils.damp(materials.arc.uniforms.uProgress.value as number, s.progress, 8, dt);349350 // The dial leans with the scroll speed, then settles351 const lean = THREE.MathUtils.clamp(s.velocity * 0.0008, -0.5, 0.5);352 tilt.current.x = THREE.MathUtils.damp(tilt.current.x, -0.38 + lean, 5, dt);353 tilt.current.y = THREE.MathUtils.damp(tilt.current.y, 0.22 - lean * 0.4, 5, dt);354 if (dialRef.current) dialRef.current.rotation.set(tilt.current.x, tilt.current.y, 0);355 s.velocity *= Math.exp(-6 * dt);356 });357358 return (359 <group ref={dialRef}>360 <mesh geometry={geometries.disc} material={materials.dial} />361 <mesh geometry={geometries.bezel} material={materials.chrome} position={[0, 0, 0.04]} />362 <mesh geometry={geometries.arc} material={materials.arc} position={[0, 0, 0.09]} />363 <primitive object={ticks} />364 <group ref={needleRef} position={[0, 0, 0.2]}>365 <mesh geometry={geometries.tip} material={materials.tip} position={[0, 0.31, 0]} />366 <mesh geometry={geometries.tail} material={materials.chrome} position={[0, -0.21, 0]} rotation={[0, 0, Math.PI]} />367 <mesh geometry={geometries.cap} material={materials.chrome} />368 </group>369 </group>370 );371});372373/**374 * Self-contained indicator: pinned to a corner of the viewport, reads the page's scroll. Clicking it375 * scrolls back to the top.376 */377function ScrollCompass3D({378 emissiveColor,379 accentColor = emissiveColor ?? "#a78bfa",380 primaryColor,381 baseColor = primaryColor ?? "#18181b",382 smoothness = 0.5,383 size = 112,384 corner = "bottom-right",385 fixed = true,386 pauseWhenOffscreen,387 lowPowerMode,388}: ScrollCompassProps) {389 const scroll = useRef<ScrollState>({ progress: 0, velocity: 0 });390 const [percent, setPercent] = useState(0);391392 useEffect(() => {393 let last = window.scrollY;394 let lastTime = performance.now();395 const update = () => {396 const max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);397 const now = performance.now();398 const y = window.scrollY;399 scroll.current.progress = THREE.MathUtils.clamp(y / max, 0, 1);400 scroll.current.velocity = ((y - last) / Math.max(1, now - lastTime)) * 1000;401 last = y;402 lastTime = now;403 setPercent(Math.round(scroll.current.progress * 100));404 };405 update();406 window.addEventListener("scroll", update, { passive: true });407 window.addEventListener("resize", update);408 return () => {409 window.removeEventListener("scroll", update);410 window.removeEventListener("resize", update);411 };412 }, []);413414 const [vertical, horizontal] = corner.split("-") as ["top" | "bottom", "left" | "right"];415 return (416 <button417 type="button"418 aria-label={`Reading progress ${percent}%. Back to top`}419 onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}420 style={{ position: fixed ? "fixed" : "absolute", [vertical]: 24, [horizontal]: 24, width: size, height: size, zIndex: 50, padding: 0, border: 0, background: "none", cursor: "pointer" }}421 >422 <UICanvas pauseWhenOffscreen={pauseWhenOffscreen} lowPowerMode={lowPowerMode} camera={{ position: [0, 0, 4.6], fov: 32 }}>423 <ambientLight intensity={0.5} />424 <directionalLight position={[-2, 3, 4]} intensity={1.6} />425 <Environment resolution={64} frames={1}>426 <Lightformer form="rect" intensity={3} position={[0, 4, 3]} rotation-x={Math.PI / 2} scale={[6, 2, 1]} />427 <Lightformer form="rect" intensity={1.5} position={[-4, 0, 2]} rotation-y={Math.PI / 2} scale={[1, 5, 1]} />428 </Environment>429 <Compass accentColor={accentColor} baseColor={baseColor} smoothness={smoothness} scroll={scroll} />430 </UICanvas>431 </button>432 );433}434435export default memo(ScrollCompass3D);
03
Drop it in a page
Updated live with the settings above.
app/page.tsx
1import ScrollCompass3D from "@/components/ScrollCompass3D";23export default function Section() {4 return (5 // The component fills this box: give it a position and a height6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>7 <ScrollCompass3D8 smoothness={0.5}9 emissiveColor="#a78bfa"10 primaryColor="#18181b"11 />12 </div>13 );14}