Skip to content

Context3D

Context3D extends CanvasContext with 3D projection capabilities. It manages view, projection, and combined view-projection matrices, and provides methods to project 3D points onto the 2D canvas.

Creation

ts
import { Context3D } from '@ripl/3d';

const context = new Context3D('#app');

Or with options:

ts
const context = new Context3D('#app', {
    fov: 60,
    near: 0.1,
    far: 1000,
});

Properties

PropertyTypeDescription
viewMatrixMatrix4The current view (camera) matrix
projectionMatrixMatrix4The current projection matrix
viewProjectionMatrixMatrix4Combined view × projection matrix
lightDirectionVector3Direction of the light source for shading

Methods

setCamera

Sets the view matrix from eye position, target, and up vector.

ts
context.setCamera([0, 0, 5], [0, 0, 0], [0, 1, 0]);

setPerspective

Updates the perspective projection.

ts
context.setPerspective(fov, near, far);

setOrthographic

Switches to orthographic projection.

ts
context.setOrthographic(left, right, bottom, top, near, far);

project

Projects a 3D point to 2D canvas coordinates.

ts
const [x, y] = context.project([1, 2, 3]);

projectDepth

Returns the projected depth of a 3D point (used for sorting).

ts
const depth = context.projectDepth([1, 2, 3]);

Demo