Camera and Controls
This guide assumes you already have a working render loop from First Scene. Here, we only focus on camera setup and controls.
What You Will Add
- one camera bound to a render target
- a perspective projection setup
- orbit controls for mouse/touch navigation
Step 1: Import Camera APIs
import {
Camera,
PerspectiveProjection,
OrthographicProjection,
OrbitCameraControls
} from "webgl";
You only need OrthographicProjection if you plan to switch projection type.
Step 2: Create a Camera
const camera = new Camera(target);
camera.transform.position.z = 3;
target should be your existing CanvasTarget.
The z offset keeps objects visible in front of the camera.
Step 3: Configure Perspective Projection
if (camera.projection instanceof PerspectiveProjection) {
camera.projection.fov = Math.PI / 3;
camera.projection.aspect = innerWidth / innerHeight;
}
Use this as the default for most real-time 3D scenes.
Step 4: Add Orbit Controls
const controls = new OrbitCameraControls(camera, canvas);
controls.distance = 4;
canvas should be the element receiving pointer input.
distance controls how far the orbit camera stays from its target.
Step 5: Update Controls in the Frame Loop
function frame() {
controls.update();
renderer.render([object, camera], device);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
Call controls.update() every frame before rendering.
If you skip it, input changes will not be applied.
Switch to Orthographic Projection
Use orthographic projection when you need no perspective foreshortening.
const ortho = new OrthographicProjection();
ortho.left = -5;
ortho.right = 5;
ortho.top = 5;
ortho.bottom = -5;
camera.projection = ortho;
For orthographic cameras, update bounds yourself when viewport shape changes.
Reference Examples
If you want to compare against an example, see:
After this works, continue with Materials and Lighting.