This document provides a comprehensive reference of all methods across the Ninth.js library with practical examples.
- Core Methods
- Scene Methods
- Object3D Methods
- Mesh Methods
- Material Methods
- Geometry Methods
- Camera Methods
- Light Methods
- Renderer Methods
- Texture Methods
- Animation Methods
- Physics Methods
- Loader Methods
Add a child object to this object.
Parameters:
object: Object3D- Object to add as child
Returns: Object3D - The added child
Example:
const parent = new Object3D();
const child = new Object3D();
parent.addChild(child);
console.log(child.parent === parent); // true
// Add with position
const child2 = new Object3D();
child2.position.set(5, 0, 0);
parent.addChild(child2);Remove a child object from this object.
Parameters:
object: Object3D- Object to remove
Returns: Object3D - The removed child
Example:
parent.removeChild(child);
console.log(child.parent); // null
// Remove specific child
parent.children.forEach(child => {
if (child.name === 'enemy') {
parent.removeChild(child);
}
});Remove this object from its parent.
Example:
child.removeFromParent();
console.log(child.parent); // nullGet child object by name.
Parameters:
name: string- Name to search forrecursive: boolean = false- Search recursively
Returns: Object3D | null - Found child or null
Example:
// Direct child only
const child = parent.getChildByName('player');
// Recursive search
const descendant = parent.getChildByName('weapon', true);Get all children of a specific type.
Parameters:
type: Function- Type/constructor to filter by
Returns: Object3D[] - Array of matching children
Example:
const meshes = parent.getChildrenByType(Mesh);
const lights = parent.getChildrenByType(Light);
const cameras = parent.getChildrenByType(Camera);Traverse all descendant objects.
Parameters:
callback: (object: Object3D) => void- Callback function
Example:
// Hide all objects named 'test'
scene.traverse((object) => {
if (object.name && object.name.startsWith('test')) {
object.visible = false;
}
});
// Count visible objects
let visibleCount = 0;
scene.traverse((object) => {
if (object.visible !== false) {
visibleCount++;
}
});Traverse only visible objects.
Parameters:
callback: (object: Object3D) => void- Callback function
Example:
// Update only visible objects
scene.traverseVisible((object) => {
if (object.userData.requiresUpdate) {
object.updateMatrixWorld();
}
});Make object look at a target position.
Parameters:
target: Vector3 | Object3D- Target position or object
Example:
// Look at position
object.lookAt(new Vector3(10, 0, 5));
// Look at object
object.lookAt(targetObject);
// Look at world position of child
object.lookAt(object.getWorldPosition(new Vector3()));Rotate object around axis.
Parameters:
axis: Vector3- Rotation axisangle: number- Rotation angle in radians
Example:
// Rotate around Y axis
object.rotateOnAxis(new Vector3(0, 1, 0), Math.PI / 2);
// Rotate around world X axis
const worldAxis = new Vector3(1, 0, 0);
object.rotateOnAxis(worldAxis, Math.PI);Rotate around X axis.
Parameters:
angle: number- Angle in radians
Example:
object.rotateX(Math.PI / 2); // 90 degreesRotate around Y axis.
Parameters:
angle: number- Angle in radians
Example:
object.rotateY(Math.PI); // 180 degreesRotate around Z axis.
Parameters:
angle: number- Angle in radians
Example:
object.rotateZ(Math.PI / 4); // 45 degreesTranslate object along axis.
Parameters:
axis: Vector3- Translation axisdistance: number- Translation distance
Example:
// Move forward in local space
object.translateOnAxis(new Vector3(0, 0, -1), 5);
// Move up in world space
object.translateOnAxis(new Vector3(0, 1, 0), 10);Translate along X axis.
Parameters:
distance: number- Translation distance
Example:
object.translateX(5); // Move 5 units rightTranslate along Y axis.
Parameters:
distance: number- Translation distance
Example:
object.translateY(10); // Move 10 units upTranslate along Z axis.
Parameters:
distance: number- Translation distance
Example:
object.translateZ(-5); // Move 5 units forwardGet world position of object.
Parameters:
target: Vector3- Vector to store result
Returns: Vector3 - World position
Example:
const worldPos = new Vector3();
object.getWorldPosition(worldPos);
console.log(worldPos);Get world quaternion rotation.
Parameters:
target: Quaternion- Quaternion to store result
Returns: Quaternion - World rotation
Example:
const worldQuat = new Quaternion();
object.getWorldQuaternion(worldQuat);Get world scale.
Parameters:
target: Vector3- Vector to store result
Returns: Vector3 - World scale
Example:
const worldScale = new Vector3();
object.getWorldScale(worldScale);Get world forward direction.
Parameters:
target: Vector3- Vector to store result
Returns: Vector3 - Forward direction
Example:
const forward = new Vector3();
object.getWorldDirection(forward);
// forward now points in object's forward directionUpdate local transformation matrix.
Example:
// Modify transform
object.position.set(5, 0, 0);
object.rotation.y = Math.PI / 2;
object.scale.set(2, 1, 2);
// Update matrix
object.updateMatrix();
// Matrix is now updated
console.log(object.matrix);Update world transformation matrix.
Parameters:
force: boolean = false- Force update even if not marked
Example:
// Force update
object.updateMatrixWorld(true);
// After modifying hierarchy
child.updateMatrixWorld();Update world matrix with hierarchy options.
Parameters:
updateParents: boolean = false- Update parent matricesupdateChildren: boolean = false- Update child matrices
Example:
// Update only this object and children
object.updateWorldMatrix(false, true);
// Update parents and this object
object.updateWorldMatrix(true, false);
// Update entire hierarchy
object.updateWorldMatrix(true, true);Copy object properties from another object.
Parameters:
source: Object3D- Source object to copy fromrecursive: boolean = true- Copy children recursively
Returns: Object3D - This object
Example:
const source = new Object3D();
source.position.set(5, 0, 0);
source.name = 'source';
const target = new Object3D();
target.copy(source);
console.log(target.position); // Vector3(5, 0, 0)
console.log(target.name); // 'source'Clone this object.
Parameters:
recursive: boolean = true- Clone children recursively
Returns: Object3D - Cloned object
Example:
const clone = object.clone(true);
// Modify clone without affecting original
clone.position.set(10, 0, 0);
clone.name = 'clone';Clean up object resources.
Example:
// Dispose object and children
object.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(mat => mat.dispose());
} else {
child.material.dispose();
}
}
});
// Remove from scene
if (object.parent) {
object.parent.removeChild(object);
}Find object by property value.
Parameters:
property: string- Property namevalue: any- Property value
Returns: Object3D | null - Found object or null
Example:
// Find first camera
const camera = scene.getObjectByProperty('isCamera', true);
// Find object with specific UUID
const object = scene.getObjectByProperty('uuid', '550e8400-e29b-41d4-a716-446655440000');Find all objects by property value.
Parameters:
property: string- Property namevalue: any- Property value
Returns: Object3D[] - Array of matching objects
Example:
// Find all objects that cast shadows
const shadowCasters = scene.getObjectsByProperty('castShadow', true);
// Find all objects with specific tag
const players = scene.getObjectsByProperty('userData.type', 'player');Add object to scene.
Parameters:
object: Object3D- Object to addname?: string- Optional name
Returns: Object3D - Added object
Example:
const cube = new Mesh(new BoxGeometry(), new MeshStandardMaterial());
scene.addObject(cube, 'player-cube');
// Add with auto-generated name
scene.addObject(cube);
console.log(cube.name); // 'Object_1' or similarRemove object from scene.
Parameters:
objectOrId: Object3D | number- Object or object ID
Returns: boolean - True if removed
Example:
// Remove by reference
scene.removeObject(cube);
// Remove by ID
scene.removeObject(cube.id);
// Remove by name
const enemy = scene.getObjectByName('enemy');
if (enemy) scene.removeObject(enemy);Find object by name.
Parameters:
name: string- Object name
Returns: Object3D | null - Found object or null
Example:
const player = scene.getObjectByName('player');
if (player) {
player.position.set(0, 0, 10);
}Find object by ID.
Parameters:
id: number- Object ID
Returns: Object3D | null - Found object or null
Example:
const object = scene.getObjectById(42);
if (object) {
object.visible = false;
}Find all objects of specific type.
Parameters:
type: Function- Type/constructor
Returns: Object3D[] - Array of matching objects
Example:
// Find all meshes
const meshes = scene.findObjectsByType(Mesh);
console.log(`Found ${meshes.length} meshes`);
// Find all lights
const lights = scene.findObjectsByType(Light);
lights.forEach(light => {
light.intensity = 0.5;
});Add camera to scene.
Parameters:
camera: Camera- Camera to add
Example:
const camera = new PerspectiveCamera(75, 16/9, 0.1, 1000);
scene.addCamera(camera);Remove camera from scene.
Parameters:
camera: Camera- Camera to remove
Example:
scene.removeCamera(camera);Set active camera for rendering.
Parameters:
camera: Camera- Camera to make active
Example:
const camera1 = new PerspectiveCamera(75, 16/9, 0.1, 1000);
const camera2 = new OrthographicCamera(-10, 10, 10, -10, 0.1, 1000);
scene.addCamera(camera1);
scene.addCamera(camera2);
scene.setActiveCamera(camera1);Add light to scene.
Parameters:
light: Light- Light to add
Example:
const ambientLight = new AmbientLight(0xffffff, 0.2);
const directionalLight = new DirectionalLight(0xffffff, 1);
scene.addLight(ambientLight);
scene.addLight(directionalLight);Remove light from scene.
Parameters:
light: Light- Light to remove
Example:
scene.removeLight(directionalLight);Render scene.
Parameters:
renderer: WebGLRenderer- Renderer to usecamera?: Camera- Optional camera override
Example:
// Render with active camera
scene.render(renderer);
// Render with specific camera
scene.render(renderer, camera);
// In animation loop
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
scene.update(deltaTime);
scene.render(renderer);
}Update scene and all objects.
Parameters:
deltaTime: number- Time elapsed since last update
Example:
const clock = new Clock();
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
scene.update(deltaTime);
renderer.render(scene, camera);
}Set scene background.
Parameters:
color: Color | Texture | null- Background color, texture, or null
Example:
// Set color background
scene.setBackground(new Color('#87CEEB')); // Sky blue
scene.setBackground(0xFF0000); // Red
// Set texture background
scene.setBackground(environmentTexture);
// Transparent background
scene.setBackground(null);Set scene fog.
Parameters:
fog: FogSettings | null- Fog settings or null
Example:
scene.setFog({
enabled: true,
color: new Color('#CCCCCC'),
near: 10,
far: 200,
type: 'linear'
});
// Disable fog
scene.setFog(null);Set ambient lighting.
Parameters:
color: Color- Ambient light colorintensity: number- Light intensity
Example:
scene.setAmbientLight(new Color(0x404040), 0.3);
// Warm ambient light
scene.setAmbientLight(new Color(0xFFA500), 0.2);Perform raycasting against mesh.
Parameters:
raycaster: Raycaster- Raycaster instanceintersects: Intersection[]- Intersections array
Example:
// Custom raycasting
const raycaster = new Raycaster();
const mouse = new Vector2();
const intersects = [];
// Set mouse position (normalized device coordinates)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Cast ray
raycaster.setFromCamera(mouse, camera);
raycaster.intersectObject(mesh, intersects);
console.log(`Hit ${intersects.length} objects`);
if (intersects.length > 0) {
console.log('First hit:', intersects[0]);
}Set material property.
Parameters:
name: string- Property namevalue: any- Property value
Example:
// Set basic properties
material.setProperty('color', new Color(1, 0, 0));
material.setProperty('opacity', 0.8);
material.setProperty('transparent', true);
// Set PBR properties
material.setProperty('metalness', 0.8);
material.setProperty('roughness', 0.2);Get material property.
Parameters:
name: string- Property name
Returns: any - Property value or undefined
Example:
const color = material.getProperty('color');
const opacity = material.getProperty('opacity');
const custom = material.getProperty('customProperty');Set multiple properties.
Parameters:
properties: Object- Property name-value pairs
Example:
material.setProperties({
color: '#FF0000',
opacity: 0.8,
transparent: true,
metalness: 0.5,
roughness: 0.3
});Set material texture.
Parameters:
name: string- Texture name/uniform nametexture: Texture- Texture objectunit?: number- Texture unit
Example:
// Set diffuse texture
material.setTexture('diffuse', textureLoader.load('diffuse.jpg'), 0);
// Set normal texture
material.setTexture('normal', normalTexture, 1);
// Set without specifying unit (auto-assign)
material.setTexture('emissive', emissiveTexture);Get material texture.
Parameters:
name: string- Texture name
Returns: TextureBinding | null - Texture binding or null
Example:
const textureBinding = material.getTexture('diffuse');
if (textureBinding) {
console.log(`Texture unit: ${textureBinding.unit}`);
}Check if material has texture.
Parameters:
name: string- Texture name
Returns: boolean - True if texture exists
Example:
if (material.hasTexture('normal')) {
console.log('Material has normal map');
}Clone material.
Returns: Material - Cloned material
Example:
const clonedMaterial = material.clone();
clonedMaterial.setProperty('color', new Color(0, 1, 0));Clean up material resources.
Example:
material.dispose();
// Clean up textures
material.textures.forEach((binding, name) => {
binding.texture.dispose();
});Add vertex attribute.
Parameters:
name: string- Attribute nameattribute: BufferAttribute- Attribute data
Example:
// Create position attribute
const positions = new Float32Array([
0, 0, 0, // Vertex 1
1, 0, 0, // Vertex 2
0, 1, 0 // Vertex 3
]);
const positionAttribute = new BufferAttribute(positions, 3);
geometry.addAttribute('position', positionAttribute);
// Add normal attribute
const normals = new Float32Array([
0, 0, 1, // Normal for all vertices
0, 0, 1,
0, 0, 1
]);
const normalAttribute = new BufferAttribute(normals, 3);
geometry.addAttribute('normal', normalAttribute);Remove vertex attribute.
Parameters:
name: string- Attribute name
Example:
geometry.removeAttribute('color');
// Check if attribute exists
if (geometry.hasAttribute('normal')) {
console.log('Geometry has normals');
}Get vertex attribute.
Parameters:
name: string- Attribute name
Returns: BufferAttribute | null - Attribute or null
Example:
const positionAttr = geometry.getAttribute('position');
if (positionAttr) {
console.log(`Position count: ${positionAttr.count}`);
console.log(`Position array:`, positionAttr.array);
}Check if geometry has attribute.
Parameters:
name: string- Attribute name
Returns: boolean - True if attribute exists
Example:
const hasPositions = geometry.hasAttribute('position');
const hasNormals = geometry.hasAttribute('normal');
const hasUVs = geometry.hasAttribute('uv');Set index buffer.
Parameters:
index: BufferAttribute- Index attribute
Example:
// Create indexed geometry
const indices = new Uint16Array([
0, 1, 2, // First triangle
2, 3, 0 // Second triangle
]);
const indexAttribute = new BufferAttribute(indices, 1);
geometry.setIndex(indexAttribute);Compute geometry bounding box.
Example:
geometry.computeBoundingBox();
const bbox = geometry.boundingBox;
console.log(`Bounding box: min=${bbox.min.toArray()}, max=${bbox.max.toArray()}`);
// Bounding box is now available for frustum cullingCompute geometry bounding sphere.
Example:
geometry.computeBoundingSphere();
const sphere = geometry.boundingSphere;
console.log(`Bounding sphere: center=${sphere.center.toArray()}, radius=${sphere.radius}`);Merge another geometry.
Parameters:
geometry: BufferGeometry- Geometry to merge
Example:
const boxGeometry = new BoxGeometry(1, 1, 1);
const sphereGeometry = new SphereGeometry(0.5, 8, 6);
boxGeometry.merge(sphereGeometry);Merge duplicate vertices.
Parameters:
tolerance: number = 1e-4- Vertex merging tolerance
Returns: BufferGeometry - Optimized geometry
Example:
const optimized = geometry.mergeVertices(1e-5);
console.log(`Optimized: ${optimized.attributes.position.count} vertices`);Recompute vertex normals.
Example:
// After deforming geometry
geometry.computeVertexNormals();
// Normals are updated for proper lightingCenter geometry at origin.
Example:
geometry.center();
// Geometry is now centered at (0, 0, 0)Normalize all normals.
Example:
geometry.normalizeNormals();
// All normals are unit lengthSet draw range for partial rendering.
Parameters:
start: number- Start indexcount: number- Number of elements to draw
Example:
// Draw only first 100 vertices
geometry.setDrawRange(0, 100);
// Draw vertices 50-100
geometry.setDrawRange(50, 50);Apply transformation matrix to geometry.
Parameters:
matrix: Matrix4- Transformation matrix
Example:
// Scale geometry
const scaleMatrix = new Matrix4().makeScale(2, 2, 2);
geometry.applyMatrix4(scaleMatrix);
// Translate geometry
const translateMatrix = new Matrix4().makeTranslation(10, 0, 0);
geometry.applyMatrix4(translateMatrix);Clone geometry.
Returns: BufferGeometry - Cloned geometry
Example:
const clonedGeometry = geometry.clone();Clean up geometry resources.
Example:
geometry.dispose();
// Free GPU buffer memoryMake camera look at target.
Parameters:
target: Vector3 | Object3D- Look target
Example:
// Look at position
camera.lookAt(new Vector3(10, 0, 0));
// Look at object
camera.lookAt(targetObject);
// Look at world position
const worldPos = new Vector3();
camera.lookAt(camera.getWorldPosition(worldPos));Update camera view matrix.
Example:
camera.updateMatrix();
console.log(camera.matrix); // View matrixUpdate camera projection matrix.
Example:
// After changing camera parameters
camera.fov = 60;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();Update camera world matrix.
Parameters:
force: boolean = false- Force update
Example:
camera.updateMatrixWorld(true);
console.log(camera.matrixWorld);Get camera world position.
Parameters:
target: Vector3- Vector to store result
Returns: Vector3 - World position
Example:
const worldPos = new Vector3();
camera.getWorldPosition(worldPos);Get camera forward direction.
Parameters:
target: Vector3- Vector to store result
Returns: Vector3 - Forward direction
Example:
const forward = new Vector3();
camera.getWorldDirection(forward);Clone camera.
Returns: Camera - Cloned camera
Example:
const clonedCamera = camera.clone();
clonedCamera.position.set(10, 0, 0);Point light at target.
Parameters:
target: Vector3 | Object3D- Look target
Example:
// Point spotlight at target
spotLight.lookAt(targetObject);
// Point directional light
directionalLight.lookAt(new Vector3(0, 0, 0));Render a scene.
Parameters:
scene: Scene- Scene to rendercamera: Camera- Camera to render from
Example:
// Basic rendering
renderer.render(scene, camera);
// In animation loop
function animate() {
requestAnimationFrame(animate);
scene.update(deltaTime);
renderer.render(scene, camera);
}Set renderer size.
Parameters:
width: number- Width in pixelsheight: number- Height in pixels
Example:
// Handle window resize
window.addEventListener('resize', () => {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});Set device pixel ratio.
Parameters:
ratio: number- Pixel ratio
Example:
// For high-DPI displays
renderer.setPixelRatio(window.devicePixelRatio);
// For performance on mobile
renderer.setPixelRatio(1);Set clear color.
Parameters:
color: Color | number- Clear coloralpha?: number- Clear alpha
Example:
// Set background color
renderer.setClearColor(0x87CEEB); // Sky blue
renderer.setClearColor('#FF0000'); // Red
// Set with alpha
renderer.setClearColor(0x000000, 0.5); // Semi-transparent clearClear framebuffer.
Parameters:
color?: boolean- Clear color bufferdepth?: boolean- Clear depth bufferstencil?: boolean- Clear stencil buffer
Example:
// Clear all buffers
renderer.clear();
// Clear only color
renderer.clear(true, false, false);
// Manual clearing for custom effects
renderer.autoClear = false;
renderer.clear(true, true, true);Compile GLSL shader.
Parameters:
source: string- Shader source codetype: number- Shader type (VERTEX_SHADER or FRAGMENT_SHADER)
Returns: WebGLShader - Compiled shader
Example:
const vertexShader = `
attribute vec3 position;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const compiledShader = renderer.compileShader(vertexShader, gl.VERTEX_SHADER);Create shader program.
Parameters:
vertexShader: WebGLShader- Vertex shaderfragmentShader: WebGLShader- Fragment shader
Returns: WebGLProgram - Linked program
Example:
const vertexShader = renderer.compileShader(vertexSource, gl.VERTEX_SHADER);
const fragmentShader = renderer.compileShader(fragmentSource, gl.FRAGMENT_SHADER);
const program = renderer.createProgram(vertexShader, fragmentShader);Get WebGL context.
Returns: WebGLRenderingContext
Example:
const gl = renderer.getContext();
console.log(`WebGL Version: ${gl.getParameter(gl.VERSION)}`);
console.log(`GPU: ${gl.getParameter(gl.RENDERER)}`);Get GPU capabilities.
Returns: WebGLCapabilities
Example:
const caps = renderer.getCapabilities();
console.log(`Max texture size: ${caps.maxTextureSize}`);
console.log(`Max vertex attributes: ${caps.maxVertexAttribs}`);
console.log(`Extensions: ${caps.extensions.join(', ')}`);Check for WebGL errors.
Returns: string[] - Array of error messages
Example:
// Check after rendering
const errors = renderer.checkError();
if (errors.length > 0) {
console.error('WebGL Errors:', errors);
}Read pixels from framebuffer.
Parameters:
x: number- X positiony: number- Y positionwidth: number- Widthheight: number- Heightformat?: number- Pixel formattype?: number- Data type
Returns: Uint8Array - Pixel data
Example:
// Read single pixel
const pixel = renderer.readPixels(100, 100, 1, 1);
console.log(`Pixel color: R=${pixel[0]}, G=${pixel[1]}, B=${pixel[2]}, A=${pixel[3]}`);
// Read region
const pixels = renderer.readPixels(0, 0, canvas.width, canvas.height);Mark texture for GPU upload.
Example:
// After modifying texture data
texture.needsUpdate = true;Clean up texture resources.
Example:
texture.dispose();Update texture transformation matrix.
Example:
texture.offset.set(0.5, 0.5);
texture.rotation = Math.PI / 2;
texture.updateMatrix();Update animation mixer.
Parameters:
deltaTime: number- Time delta in seconds
Example:
const clock = new Clock();
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
mixer.update(deltaTime);
renderer.render(scene, camera);
}Create animation action.
Parameters:
clip: AnimationClip- Animation cliproot?: Object3D- Root object
Returns: AnimationAction - Animation action
Example:
const walkClip = model.animations.find(clip => clip.name === 'walk');
const walkAction = mixer.clipAction(walkClip);
walkAction.play();Stop all animation actions.
Example:
mixer.stopAllAction();Remove clip from cache.
Parameters:
clip: AnimationClip- Animation clip
Example:
mixer.uncacheClip(walkClip);Start playing animation.
Example:
action.play();Stop playing animation.
Example:
action.stop();Pause animation.
Example:
action.pause();Resume paused animation.
Example:
action.resume();Reset animation to beginning.
Example:
action.reset();Set animation loop mode.
Parameters:
loop: LoopMode- Loop moderepetitions?: number- Number of repetitions
Example:
action.setLoop('LoopOnce'); // Play once
action.setLoop('LoopRepeat'); // Loop forever
action.setLoop('LoopPingPong', 5); // Ping-pong 5 timesSet animation weight.
Parameters:
weight: number- Weight (0-1)
Example:
action.setEffectiveWeight(0.5); // 50% influenceFade in animation.
Parameters:
duration: number- Fade duration in seconds
Example:
action.fadeIn(1.0); // 1 second fade inFade out animation.
Parameters:
duration: number- Fade duration in seconds
Example:
action.fadeOut(0.5); // 0.5 second fade outLoad resource.
Parameters:
url: string- Resource URLonLoad: Function- Load success callbackonProgress: Function- Progress callbackonError: Function- Error callback
Example:
const loader = new GLTFLoader();
loader.load(
'model.glb',
(gltf) => {
console.log('Model loaded:', gltf);
scene.addObject(gltf.scene);
},
(progress) => {
console.log('Loading progress:', progress.loaded / progress.total * 100 + '%');
},
(error) => {
console.error('Error loading model:', error);
}
);Load resource asynchronously.
Parameters:
url: string- Resource URL
Returns: Promise - Promise that resolves with loaded resource
Example:
const loader = new GLTFLoader();
try {
const gltf = await loader.loadAsync('model.glb');
scene.addObject(gltf.scene);
} catch (error) {
console.error('Error loading model:', error);
}Parse JSON data.
Parameters:
json: Object | string- JSON data
Example:
const jsonData = await fetch('model.json').then(r => r.json());
const geometry = loader.parse(jsonData);Set CORS mode.
Parameters:
crossOrigin: string- CORS mode
Example:
loader.setCrossOrigin('anonymous');Set base path.
Parameters:
path: string- Base path for relative URLs
Example:
loader.setPath('/models/');
loader.load('character.glb', onLoad);Add event listener.
Parameters:
event: string- Event namelistener: Function- Event handleroptions?: Object- Listener options
Returns: Function - Unsubscribe function
Example:
// Add listener
const unsubscribe = scene.on('objectAdded', (data) => {
console.log('Object added:', data.object.name);
});
// Or use returned function
unsubscribe();Add one-time event listener.
Parameters:
event: string- Event namelistener: Function- Event handleroptions?: Object- Listener options
Returns: Function - Unsubscribe function
Example:
scene.once('loadComplete', (data) => {
console.log('First load completed!');
});Remove event listener.
Parameters:
event: string- Event namelistener: Function- Event handler
Example:
function handleObjectAdded(data) {
console.log('Object added:', data.object.name);
}
scene.on('objectAdded', handleObjectAdded);
// Later...
scene.off('objectAdded', handleObjectAdded);Emit event.
Parameters:
event: string- Event namedata?: any- Event data
Example:
scene.emit('customEvent', { message: 'Hello' });
scene.emit('objectAdded', { object: cube });Remove all listeners.
Parameters:
event?: string- Event name (optional)
Example:
// Remove all listeners for specific event
scene.removeAllListeners('objectAdded');
// Remove all listeners
scene.removeAllListeners();Set vector components.
Parameters:
x: number- X componenty: number- Y componentz: number- Z component
Example:
const vector = new Vector3();
vector.set(10, 5, 0);Copy from another vector.
Parameters:
v: Vector3- Source vector
Example:
const source = new Vector3(10, 5, 0);
const target = new Vector3();
target.copy(source);Add vector.
Parameters:
v: Vector3- Vector to add
Example:
const vector = new Vector3(1, 0, 0);
vector.add(new Vector3(2, 3, 4)); // Now (3, 3, 4)Subtract vector.
Parameters:
v: Vector3- Vector to subtract
Example:
const vector = new Vector3(5, 3, 1);
vector.sub(new Vector3(2, 1, 0)); // Now (3, 2, 1)Multiply by scalar.
Parameters:
s: number- Scalar value
Example:
const vector = new Vector3(1, 2, 3);
vector.multiplyScalar(2); // Now (2, 4, 6)Get vector length.
Returns: number - Vector length
Example:
const vector = new Vector3(3, 4, 0);
const length = vector.length(); // 5Get distance to another vector.
Parameters:
v: Vector3- Target vector
Returns: number - Distance
Example:
const v1 = new Vector3(0, 0, 0);
const v2 = new Vector3(3, 4, 0);
const distance = v1.distanceTo(v2); // 5Normalize vector (make length 1).
Example:
const vector = new Vector3(10, 0, 0);
vector.normalize(); // Now (1, 0, 0)Cross product.
Parameters:
v: Vector3- Other vector
Returns: Vector3 - Cross product result
Example:
const v1 = new Vector3(1, 0, 0);
const v2 = new Vector3(0, 1, 0);
const cross = v1.cross(v2); // (0, 0, 1)Dot product.
Parameters:
v: Vector3- Other vector
Returns: number - Dot product
Example:
const v1 = new Vector3(1, 2, 3);
const v2 = new Vector3(4, 5, 6);
const dot = v1.dot(v2); // 32Set to identity matrix.
Example:
const matrix = new Matrix4();
matrix.identity();Multiply by matrix.
Parameters:
m: Matrix4- Matrix to multiply by
Example:
const m1 = new Matrix4().makeRotationY(Math.PI / 2);
const m2 = new Matrix4().makeTranslation(10, 0, 0);
m1.multiply(m2);Multiply by scalar.
Parameters:
s: number- Scalar value
Example:
const matrix = new Matrix4();
matrix.multiplyScalar(2);Get matrix determinant.
Returns: number - Determinant
Example:
const matrix = new Matrix4();
const det = matrix.determinant();Invert matrix.
Example:
const matrix = new Matrix4();
matrix.invert();Transpose matrix.
Example:
const matrix = new Matrix4();
matrix.transpose();Compose transformation.
Parameters:
position: Vector3- Positionquaternion: Quaternion- Rotationscale: Vector3- Scale
Example:
const matrix = new Matrix4();
const position = new Vector3(10, 0, 0);
const quaternion = new Quaternion();
const scale = new Vector3(2, 1, 1);
matrix.compose(position, quaternion, scale);Decompose matrix.
Parameters:
position: Vector3- Position outputquaternion: Quaternion- Rotation outputscale: Vector3- Scale output
Example:
const position = new Vector3();
const quaternion = new Quaternion();
const scale = new Vector3();
matrix.decompose(position, quaternion, scale);Make X rotation matrix.
Parameters:
angle: number- Angle in radians
Example:
const matrix = new Matrix4();
matrix.makeRotationX(Math.PI / 2);Make Y rotation matrix.
Parameters:
angle: number- Angle in radians
Example:
const matrix = new Matrix4();
matrix.makeRotationY(Math.PI);Make Z rotation matrix.
Parameters:
angle: number- Angle in radians
Example:
const matrix = new Matrix4();
matrix.makeRotationZ(Math.PI / 4);Make translation matrix.
Parameters:
x: number- X translationy: number- Y translationz: number- Z translation
Example:
const matrix = new Matrix4();
matrix.makeTranslation(10, 5, 0);Make scale matrix.
Parameters:
x: number- X scaley: number- Y scalez: number- Z scale
Example:
const matrix = new Matrix4();
matrix.makeScale(2, 1, 2);This comprehensive method reference covers all major methods across the Ninth.js library with practical examples for each function. Each method includes parameter descriptions, return values, and real-world usage examples to help developers understand how to use the library effectively.