Module 28 - SceneView and the Camera
Level 6 · The Third Dimension · 🟠 · 4 hours · Prereq: Module 27
What you'll build
A cinematic camera controller: bookmarks that fly between viewpoints, an orbit mode that circles a target, a first-person walk mode, and a camera-path animator that follows a Catmull-Rom spline through waypoints.
Why this matters
A SceneView's camera has six degrees of freedom instead of a 2D view's three, and the API is
different enough that 2D habits produce broken results. Camera control is also the single
biggest determinant of whether a 3D application feels professional or feels like a tech demo.
Concepts
1. SceneView vs MapView
import SceneView from "@arcgis/core/views/SceneView.js";
const view = new SceneView({
container: "viewDiv",
map,
camera: {
position: { longitude: -76.481, latitude: 44.221, z: 800 },
heading: 25,
tilt: 65,
},
viewingMode: "global", // "global" | "local"
qualityProfile: "high", // "low" | "medium" | "high"
environment: { /* Module 32 */ },
});
Everything from Modules 5, 18-22 applies unchanged: view.when(), whenLayerView,
goTo, hitTest, ui, graphics, popup, reactiveUtils. The differences are the camera,
the ground, and the environment.
Bundle cost: importing SceneView adds roughly 500 KB gzipped. Module 4's experiment. If
your app has a 2D-only route, load it dynamically.
2. The Camera
view.camera = {
position: { longitude: -76.481, latitude: 44.221, z: 800 }, // z in METRES above sea level
heading: 25, // 0 = north, 90 = east, clockwise
tilt: 65, // 0 = straight down, 90 = horizon, > 90 = looking up
fov: 55, // field of view in degrees
};
| Property | Range | Note |
|---|---|---|
position.z |
metres | Absolute height above sea level, not above ground |
heading |
0-360 | Compass bearing of the view direction |
tilt |
0-180 | 0 = nadir (top-down), 90 = horizontal, > 90 = looking upward |
fov |
1-160 | 55 default; smaller = telephoto, larger = wide angle |
position.z being absolute is the first surprise. Setting z: 100 in Denver (elevation
1,600 m) puts the camera 1,500 m underground. There is no "above ground" camera property - you
must query the elevation and add to it.
const groundZ = await view.map.ground.queryElevation(point);
view.camera = {
position: { ...point, z: groundZ.geometry.z + 100 }, // 100 m above the terrain
heading: 0, tilt: 75,
};
3. view.zoom and view.scale in 3D
Both exist and both are derived from the camera:
view.zoom; // approximate equivalent zoom level
view.scale; // approximate map scale at the view centre
view.center; // the point at the centre of the view (on the ground)
Setting them works and produces a top-down camera:
view.zoom = 15; // ⚠️ resets tilt to 0 in most cases
Use camera for anything that should preserve tilt and heading. Use zoom/scale/goTo
with a geometry when you want the SDK to frame something and don't care about the angle.
4. goTo in 3D
// Frame a geometry - the SDK picks a camera
await view.goTo(polygon);
// Preserve the current angle while moving
await view.goTo({ target: point, tilt: view.camera.tilt, heading: view.camera.heading });
// A full camera
await view.goTo({
position: { longitude, latitude, z: 1200 },
heading: 45,
tilt: 70,
});
// With animation options
await view.goTo(target, {
duration: 3000,
easing: "in-out-cubic", // "linear" | "ease-in" | "ease-out" | "ease-in-out" |
// "in-cubic" | "out-cubic" | "in-out-cubic" |
// "in-expo" | "out-expo" | "in-out-expo" | function
speedFactor: 1,
maxDuration: 8000,
});
goTo with only a target resets tilt to a default. If your app has a tilted view and a
"zoom to feature" button that flattens it, that's why. Pass the current tilt and heading
explicitly.
Path shape: the SDK interpolates in a way that arcs upward for long distances (so you fly over rather than through terrain) and stays low for short ones. You don't control the arc directly - for that, animate the camera yourself (§8).
5. viewingMode: "global" vs "local"
global |
local |
|
|---|---|---|
| Earth shape | Curved ellipsoid | Flat slab |
| Extent | The whole planet | A bounded box you define |
| Below ground | Not viewable | Viewable |
| Clipping | No | clippingArea |
| Slice widget | Limited | Full |
| Sky/atmosphere | Yes | Optional |
| Use for | Regional and global scenes | Site models, underground, BIM |
const view = new SceneView({
map,
viewingMode: "local",
clippingArea: {
xmin: -8515000, ymin: 5498000, xmax: -8510000, ymax: 5503000,
spatialReference: { wkid: 3857 },
},
});
local mode is what you need for underground utilities, building interiors, and slicing.
In global mode the camera cannot go below the ellipsoid surface, which makes below-ground
work impossible.
You cannot switch modes on a live view. It's a constructor-time decision; changing it means building a new view.
6. Constraints
view.constraints = {
altitude: { min: 50, max: 30000 }, // metres
tilt: { max: 85 }, // stop the user looking at the sky
collision: { enabled: true }, // camera can't pass through terrain/buildings
clipDistance: { near: 1, far: 50000 }, // depth buffer range
};
collision.enabled is the difference between a walk-through and a clip-through. With it on,
the camera stops at the ground and at buildings. With it off, you fly through walls.
clipDistance matters more in 3D than you'd expect. A near/far ratio above ~10,000:1 causes
z-fighting - surfaces flickering because the depth buffer can't distinguish them. If your
building faces shimmer at distance, tighten near.
7. Camera state and readouts
reactiveUtils.watch(
() => view.camera,
(camera) => {
readout.textContent =
`${camera.position.longitude.toFixed(5)}, ${camera.position.latitude.toFixed(5)} ` +
`· ${Math.round(camera.position.z)} m · ${Math.round(camera.heading)}° ` +
`· tilt ${Math.round(camera.tilt)}°`;
}
);
view.camera is replaced wholesale on every change, not mutated. That's why watching it
works and why view.camera.tilt = 45 does nothing - you must assign a whole camera:
// ❌ no effect
view.camera.tilt = 45;
// ✅
const camera = view.camera.clone();
camera.tilt = 45;
view.camera = camera;
8. Animating the camera yourself
goTo covers most cases. For a cinematic path through waypoints you drive the camera per
frame:
function animate(frameCallback, durationMs) {
return new Promise((resolve) => {
const start = performance.now();
let cancelled = false;
function frame(now) {
if (cancelled) return resolve("cancelled");
const t = Math.min((now - start) / durationMs, 1);
frameCallback(t);
if (t < 1) requestAnimationFrame(frame);
else resolve("done");
}
requestAnimationFrame(frame);
animate.cancel = () => { cancelled = true; };
});
}
Assigning view.camera every frame is fine - the SDK is designed for it. What is not fine
is calling goTo every frame; each call cancels the previous and you get stutter.
Build it - the camera controller
Step 1 - Camera utilities
// src/camera/utils.js
/** Camera at a fixed height ABOVE GROUND at a point. */
export async function cameraAboveGround(view, point, { heightM = 200, heading = 0, tilt = 70 } = {}) {
const { geometry } = await view.map.ground.queryElevation(point);
return {
position: {
longitude: point.longitude ?? point.x,
latitude: point.latitude ?? point.y,
z: (geometry.z ?? 0) + heightM,
spatialReference: point.spatialReference,
},
heading,
tilt,
};
}
/** A camera looking AT a target from a given distance, heading and tilt. */
export function cameraLookingAt(target, { distanceM = 500, heading = 0, tilt = 65 } = {}) {
const tiltRad = (tilt * Math.PI) / 180;
const headingRad = (heading * Math.PI) / 180;
// Horizontal offset from the target, opposite the heading
const horizontal = distanceM * Math.sin(tiltRad);
const vertical = distanceM * Math.cos(tiltRad);
// Convert metres to degrees. Latitude is ~111,320 m/deg everywhere;
// longitude shrinks by cos(latitude).
const METRES_PER_DEG_LAT = 111320;
const lat = target.latitude ?? target.y;
const metresPerDegLon = METRES_PER_DEG_LAT * Math.cos((lat * Math.PI) / 180);
return {
position: {
longitude: (target.longitude ?? target.x) - (horizontal * Math.sin(headingRad)) / metresPerDegLon,
latitude: lat - (horizontal * Math.cos(headingRad)) / METRES_PER_DEG_LAT,
z: (target.z ?? 0) + vertical,
spatialReference: { wkid: 4326 },
},
heading,
tilt,
};
}
/** Shortest angular difference, so a 350° → 10° turn goes +20° not −340°. */
export function shortestAngle(from, to) {
const diff = ((to - from + 540) % 360) - 180;
return diff;
}
export function lerpAngle(from, to, t) {
return from + shortestAngle(from, to) * t;
}
shortestAngle is the detail that makes camera animation not look silly. Interpolating
heading from 350° to 10° linearly spins the camera 340° the wrong way. Every 3D camera system
needs this function and it's four lines.
Step 2 - Orbit mode
// src/camera/orbit.js
import { HandleRegistry } from "../handleRegistry.js";
/**
* Circle a target point at a fixed distance and tilt.
* Stops on any user interaction, which is what users expect.
*/
export function createOrbit({ view, onStateChange }) {
const registry = new HandleRegistry();
let running = false;
let frameId = null;
function start(target, { distanceM = 600, tilt = 65, degreesPerSecond = 12 } = {}) {
stop();
running = true;
onStateChange?.({ running: true });
let heading = view.camera.heading;
let last = performance.now();
const step = (now) => {
if (!running) return;
const dt = (now - last) / 1000;
last = now;
heading = (heading + degreesPerSecond * dt) % 360;
view.camera = cameraOnCircle(target, distanceM, heading, tilt);
frameId = requestAnimationFrame(step);
};
frameId = requestAnimationFrame(step);
}
function stop() {
running = false;
if (frameId !== null) cancelAnimationFrame(frameId);
frameId = null;
onStateChange?.({ running: false });
}
// Any user drag or wheel cancels the orbit. Without this, the user fights
// the animation and it feels broken.
registry.add(view.on("drag", stop), "orbit");
registry.add(view.on("mouse-wheel", stop), "orbit");
registry.add(view.on("key-down", stop), "orbit");
return { start, stop, get running() { return running; }, destroy() { stop(); registry.destroy(); } };
}
function cameraOnCircle(target, distanceM, heading, tilt) {
const tiltRad = (tilt * Math.PI) / 180;
const headingRad = (heading * Math.PI) / 180;
const horizontal = distanceM * Math.sin(tiltRad);
const vertical = distanceM * Math.cos(tiltRad);
const METRES_PER_DEG_LAT = 111320;
const metresPerDegLon = METRES_PER_DEG_LAT * Math.cos((target.latitude * Math.PI) / 180);
return {
position: {
longitude: target.longitude - (horizontal * Math.sin(headingRad)) / metresPerDegLon,
latitude: target.latitude - (horizontal * Math.cos(headingRad)) / METRES_PER_DEG_LAT,
z: (target.z ?? 0) + vertical,
spatialReference: { wkid: 4326 },
},
heading,
tilt,
};
}
Cancelling on user input is the detail that separates a polished orbit from an annoying one. A user who grabs the map while it's orbiting expects to take control.
Step 3 - The spline camera path
// src/camera/flyPath.js
/**
* Catmull-Rom spline through waypoints.
*
* Pure functions, deliberately outside any hook or class - this is maths, not
* state, and keeping it separate makes it testable without a view.
*/
/** Catmull-Rom interpolation between p1 and p2, with p0 and p3 as tangent controls. */
function catmullRom(p0, p1, p2, p3, t) {
const t2 = t * t;
const t3 = t2 * t;
return 0.5 * (
2 * p1 +
(-p0 + p2) * t +
(2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 +
(-p0 + 3 * p1 - 3 * p2 + p3) * t3
);
}
/**
* Sample a smooth path through waypoints.
* @param {Array<{longitude:number, latitude:number, z:number, heading:number, tilt:number}>} waypoints
* @param {number} samplesPerSegment
* @returns {Array<Camera>}
*/
export function buildFlyPath(waypoints, samplesPerSegment = 40) {
if (waypoints.length < 2) return waypoints.map(toCamera);
// Duplicate the endpoints so the spline passes through the first and last
// waypoints instead of using them only as tangent controls.
const points = [waypoints[0], ...waypoints, waypoints.at(-1)];
const path = [];
for (let i = 1; i < points.length - 2; i++) {
const [p0, p1, p2, p3] = [points[i - 1], points[i], points[i + 1], points[i + 2]];
for (let s = 0; s < samplesPerSegment; s++) {
const t = s / samplesPerSegment;
path.push({
position: {
longitude: catmullRom(p0.longitude, p1.longitude, p2.longitude, p3.longitude, t),
latitude: catmullRom(p0.latitude, p1.latitude, p2.latitude, p3.latitude, t),
z: catmullRom(p0.z, p1.z, p2.z, p3.z, t),
spatialReference: { wkid: 4326 },
},
// Angles interpolate linearly along the shortest arc - a spline on
// heading would overshoot past the waypoint value and look wrong.
heading: lerpAngleAlong(p1.heading, p2.heading, t),
tilt: p1.tilt + (p2.tilt - p1.tilt) * t,
});
}
}
path.push(toCamera(waypoints.at(-1)));
return path;
}
function lerpAngleAlong(from, to, t) {
const diff = ((to - from + 540) % 360) - 180;
return (from + diff * t + 360) % 360;
}
const toCamera = (w) => ({
position: { longitude: w.longitude, latitude: w.latitude, z: w.z,
spatialReference: { wkid: 4326 } },
heading: w.heading,
tilt: w.tilt,
});
Position uses a spline; angles use linear interpolation along the shortest arc. That mixed approach is deliberate - a Catmull-Rom on heading overshoots past each waypoint's value, which reads as the camera "wobbling" at every waypoint.
This is the same design as this repository's
flycam/flyPath.js: "holds the Catmull-Rom spline maths - pure, module-level, and deliberately outside the hook."
Step 4 - The player
// src/camera/flyPlayer.js
import { buildFlyPath } from "./flyPath.js";
import { HandleRegistry } from "../handleRegistry.js";
export function createFlyPlayer({ view, onProgress, onStateChange }) {
const registry = new HandleRegistry();
let path = [];
let index = 0;
let running = false;
let frameId = null;
let speed = 1;
function load(waypoints) {
path = buildFlyPath(waypoints, 40);
index = 0;
onProgress?.({ index: 0, total: path.length });
}
function play() {
if (!path.length || running) return;
running = true;
onStateChange?.({ running: true });
let last = performance.now();
const FRAMES_PER_SECOND = 30; // path samples consumed per second at speed 1
const step = (now) => {
if (!running) return;
const dt = (now - last) / 1000;
last = now;
index += dt * FRAMES_PER_SECOND * speed;
if (index >= path.length - 1) {
index = path.length - 1;
view.camera = path[Math.floor(index)];
stop();
onProgress?.({ index: path.length - 1, total: path.length, finished: true });
return;
}
// Assigning the camera directly is correct here. Calling goTo() per
// frame would cancel the previous animation every frame and stutter.
view.camera = path[Math.floor(index)];
onProgress?.({ index: Math.floor(index), total: path.length });
frameId = requestAnimationFrame(step);
};
frameId = requestAnimationFrame(step);
}
function pause() { stop(); }
function stop() {
running = false;
if (frameId !== null) cancelAnimationFrame(frameId);
frameId = null;
onStateChange?.({ running: false });
}
function seek(fraction) {
if (!path.length) return;
index = Math.max(0, Math.min(fraction * (path.length - 1), path.length - 1));
view.camera = path[Math.floor(index)];
onProgress?.({ index: Math.floor(index), total: path.length });
}
registry.add(view.on("drag", pause), "fly");
return {
load, play, pause, seek,
set speed(value) { speed = Math.max(0.1, Math.min(value, 8)); },
get speed() { return speed; },
get running() { return running; },
destroy() { stop(); registry.destroy(); },
};
}
Step 5 - Underground and clipping
// src/camera/undergroundView.js
import SceneView from "@arcgis/core/views/SceneView.js";
/**
* A local-mode view for looking at underground infrastructure.
* Global mode cannot place the camera below the ellipsoid.
*/
export function createUndergroundView({ container, map, extent }) {
const view = new SceneView({
container,
map,
viewingMode: "local",
clippingArea: extent,
camera: {
position: {
longitude: (extent.xmin + extent.xmax) / 2,
latitude: (extent.ymin + extent.ymax) / 2,
z: -50,
spatialReference: extent.spatialReference,
},
heading: 0,
tilt: 100, // > 90 = looking upward, from below ground
},
constraints: {
// Allow the camera below sea level
altitude: { min: -500, max: 5000 },
collision: { enabled: false }, // otherwise it can't go underground
clipDistance: { near: 1, far: 20000 },
},
environment: {
// Terrain must be see-through to view what's beneath it
background: { type: "color", color: [20, 24, 34, 1] },
starsEnabled: false,
atmosphereEnabled: false,
},
});
// The ground has to be transparent, or you're looking at the underside of a wall
view.when(() => {
map.ground.opacity = 0.4;
map.ground.navigationConstraint = { type: "none" }; // camera may pass through
});
return view;
}
Four things all have to be right for underground viewing, and missing any one gives you a black screen:
viewingMode: "local"constraints.altitude.minbelow zerocollision.enabled: falseground.navigationConstraint = { type: "none" }and a reducedground.opacity
This is worth writing down because the failure mode (nothing visible) gives no hint about which of the four is missing.
How it works
Why position.z is absolute
The camera lives in a 3D Cartesian frame anchored to the ellipsoid. "Above ground" isn't a property of that frame - it's a relationship to a terrain surface that has to be queried, asynchronously, and that changes as the camera moves.
Making z absolute keeps the camera a pure geometric object. The cost is that "100 m above the
ground" is your job.
Why tilt can exceed 90
At tilt = 90 the camera looks at the horizon. Beyond that it looks upward - which is
meaningless from above ground but essential from below it, or from inside a building looking
at a ceiling.
The constraint tilt: { max: 85 } exists because letting a user tilt past the horizon in a
normal scene is disorienting and usually accidental.
Why z-fighting happens and what fixes it
The depth buffer has finite precision (typically 24 bits), distributed non-linearly - most
of it near the camera. With near: 0.1 and far: 50000, surfaces at 10 km share almost no
depth precision, so which one draws in front flickers per frame.
The fix is always to raise near, not to lower far. Doubling near buys far more precision
than halving far.
Why local mode allows clipping
In global mode, "outside the clipping area" is a region on a sphere, and the concept of a
bounding box doesn't cleanly apply. local mode's flat slab has a natural axis-aligned box,
so clipping, slicing, and below-surface viewing all have well-defined semantics.
That's why the Slice widget's full capability is local-only (Module 33).
Common mistakes
Treating position.z as height above ground.
Underground cameras in mountainous terrain.
Mutating view.camera.tilt.
The camera is replaced wholesale. Clone, modify, assign.
goTo(geometry) in a tilted view.
Resets the tilt. Pass tilt and heading explicitly.
Linear heading interpolation across 0°. The camera spins the long way round.
Calling goTo per frame.
Each call cancels the previous. Assign view.camera instead.
Not cancelling an animation on user input. The user fights the camera.
Importing SceneView in a 2D-only route.
+500 KB.
near: 0.01 with far: 100000.
Z-fighting across the whole scene.
Trying to switch viewingMode at runtime.
Constructor-only. Rebuild the view.
Exercises
Exercise 28.1 - The full camera controller
Build:
- Bookmarks storing full cameras, with fly-to
- Orbit mode with speed and distance controls
- A waypoint editor: click to add, drag to reorder, set height and tilt per waypoint
- Spline path playback with play/pause/seek/speed
- A live camera readout
- Export/import the path as JSON
Exercise 28.2 - Height above ground
Write flyToGroundLevel(view, point, heightAboveGroundM) that:
- Queries the terrain elevation
- Positions the camera that height above it
- Handles the query failing (no elevation data) by falling back to sea level plus the height
- Works in both
globalandlocalmode
Test it in Denver, in the Netherlands, and over the ocean.
Exercise 28.3 - Z-fighting, reproduced
Build a scene with two coplanar polygons a few centimetres apart.
- Set
clipDistance: { near: 0.01, far: 100000 }and observe - Raise
nearprogressively and record when the flicker stops - Lower
farinstead and record whether it helps as much - Write down the ratio at which it becomes acceptable
Exercise 28.4 - Underground
Build the underground viewer for a utilities scene (or fake it with extruded polygons at negative Z).
Deliberately break each of the four requirements in turn and record the symptom of each. That table is worth more than the working code.
Checkpoint
- Is
camera.position.zabove sea level or above ground? - Why does
view.camera.tilt = 45do nothing? - What does
goTo(geometry)do to your tilt? - Why interpolate heading along the shortest arc?
- What are the four things needed to view underground?
- What causes z-fighting and what's the right fix?
- Why can't you switch
viewingModeat runtime?
- Above sea level - absolute. "Above ground" requires querying the terrain elevation and adding to it.
view.camerais replaced wholesale on assignment, not mutated in place. Clone it, change the clone, assign it back.- Resets it to a default framing angle. Pass
tiltandheadingexplicitly to preserve them. - Linear interpolation from 350° to 10° goes the long way (−340°), spinning the camera almost full circle.
viewingMode: "local",constraints.altitude.minbelow 0,collision.enabled: false, andground.navigationConstraint = { type: "none" }with reduced ground opacity.- Finite, non-linearly distributed depth-buffer precision - distant surfaces share too few
depth values. Raise
clipDistance.near; that buys far more precision than loweringfar. - It determines the entire coordinate frame and rendering pipeline, which are established when the view is constructed. Build a new view instead.
Further reading
- https://developers.arcgis.com/javascript/latest/api-reference/esri-Camera.html
- https://developers.arcgis.com/javascript/latest/api-reference/esri-views-SceneView.html
- https://developers.arcgis.com/javascript/latest/sample-code/scene-animate-camera/
- https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline