Search notes:

three.js

Using (importing) three.js

As of version r147, the preferred way to use three.js is via es6 modules and import maps:
<script type='importmap'>
  {
    "imports": {
      "three"        : "https://cdn.jsdelivr.net/npm/three@0.172.0/build/three.module.js",
      "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.172.0/examples/jsm/"
    }
  }
</script>

<script type='module' src='app.js'></script>
app.js:
import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';

Scene, camera and renderer

A three.js application needs at least a scene, a camera and a renderer:
import * as THREE from 'three';

const camera   = new THREE.PerspectiveCamera(fovCamera, window.innerWidth/window.innerHeight, frustumNear, frustumFar);
const scene    = new THREE.Scene();
const renderer = new THREE.WebGLRenderer({antialias: true})

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);
The camera and scene objects are passed to renderer.render() in order to render a scene as viewed from the camera.

Scene

A Scene inherits from Object3D and extends it with some properties of which the most interesting ones are:
A scene is (typically?) rendered by a renderer (WebGLRenderer or WebGPURenderer (or CanvasRenderer? or others?))
The objects of a scene are arranged hierarchically in a scene graph.

Camera

Abstract base class for cameras.
The most frequently used derived classes are PerspectiveCamera and OrthographicCamera.
Although I have seen examples where a camera is explicitely added to a scene, it is apparently not necessary to do so. (because the influence of the camara is being taken care of with in the line renderer.render(scene, camera).
It's worth noting that a camera can be added to an object such as a car driving through a scene.
For performance reasons, a camera has a frustum (represented by a Frustum object). Objects outside the frustum are not rendered.

Constructing a perspective camera

A «full screen» camera is typically created like so:
const camera = new THREE.PerspectiveCamera(
   45,                                     // field of view (fov)
   window.innerWidth / window.innerHeight, // aspect
   0.1, 10000                              // near, far
);

lookAt

camera.lookAt(new THREE.Vector3(x, y, z));
camera.lookAt(mesh_abc.position);

CameraHelper

CameraHelper inherits from LineSegments.
An instance of a CameraHelper object uses line segments to visualize the frustum of a camera.
const camHlp = new THREE.CameraHelper(camera);
scene.add(camHlp);
In the render loop:
camHlp.update();

Sprite objects

Sprite objects are planes that always face towards the camera (i. e. they're billboarded).
A sprite object can be used for texts or distant objects.

WebGLRenderer

An instance of a WebGLRenderer renders a scene using a camera.
See also the WebGPURenderer class.
WebGLRenderer inherits from no other class.
Members:
autoClear boolean Whether the renderer should automatically clear its output before rendering a frame or not. Default is true.
autoClearColor boolean If WebGLRenderer.autoClear set to true, whether the renderer should clear the color buffer or not. Default is true.
autoClearDepth boolean If WebGLRenderer.autoClear set to true, whether the renderer should clear the depth buffer or not. Default is true.
autoClearStencil boolean If WebGLRenderer.autoClear set to true, whether the renderer should clear the stencil buffer or not. Default is true.
capabilities WebGLRenderer~Capabilities Holds details about the capabilities of the current rendering context. .clippingPlanes : Array.<Plane>
coordinateSystem WebGLCoordinateSystem | WebGPUCoordinateSystem (readonly) Defines the coordinate system of the renderer. In WebGLRenderer, the value is always WebGLCoordinateSystem. Default is WebGLCoordinateSystem.
debug Object A object with debug configuration settings.
domElement HTMLCanvasElement | OffscreenCanvas A canvas where the renderer draws its output. This is automatically created by the renderer in the constructor (if not provided already); you just need to add it to your page like so: document.body.appendChild( renderer.domElement );
extensions Object Provides methods for retrieving and testing WebGL extensions. get(extensionName:string): Used to check whether a WebGL extension is supported and return the extension object if available.
info WebGLRenderer~Info Holds a series of statistical information about the GPU memory and the rendering process. Useful for debugging and monitoring.
isWebGLRenderer boolean (readonly) This flag can be used for type testing. Default is true.
localClippingEnabled boolean Whether the renderer respects object-level clipping planes or not. Default is false.
outputColorSpace SRGBColorSpace | LinearSRGBColorSpace Defines the output color space of the renderer. Default is SRGBColorSpace.
properties Object Used to track properties of other objects like native WebGL objects.
renderLists Object
shadowMap WebGLRenderer~ShadowMap Interface for managing shadows.
sortObjects boolean
state Object
toneMapping NoToneMapping | LinearToneMapping | ReinhardToneMapping | CineonToneMapping | ACESFilmicToneMapping | CustomToneMapping | AgXToneMapping | NeutralToneMapping The tone mapping technique of the renderer. Default is NoToneMapping.
toneMappingExposure number Exposure level of tone mapping. Default is 1.
transmissionResolutionScale number The normalized resolution scale for the transmission render target, measured in percentage of viewport dimensions. Lowering this value can result in significant performance improvements when using MeshPhysicalMaterial#transmission. Default is 1.
xr WebXRManager A reference to the XR manager.
clear() Tells the renderer to clear its color, depth or stencil drawing buffer(s). This method initializes the buffers to the current clear color values.
clearColor() Clears the color buffer. Equivalent to calling renderer.clear(true, false, false).
clearDepth() Clears the depth buffer. Equivalent to calling renderer.clear(false, true, false).
clearStencil() Clears the stencil buffer. Equivalent to calling renderer.clear(false, false, true).
compile(scene: Object3D, camera: Camera, targetScene: Scene): Set.<Material> Compiles all materials in the scene with the camera. This is useful to precompile shaders before the first rendering. If you want to add a 3D object to an existing scene, use the third optional parameter for applying the target scene.
compileAsync(scene: Object3D, camera: Camera, targetScene: Scene): Promise (async) Asynchronous version of WebGLRenderer.compile.
copyFramebufferToTexture(texture: FramebufferTexture, position: Vector2, level: number) Copies pixels from the current bound framebuffer into the given texture.
copyTextureToTexture(srcTexture: Texture, dstTexture: Texture, srcRegion: Box2 | Box3, dstPosition: Vector2 | Vector3, srcLevel: number, dstLevel: number) Copies data of the given source texture into a destination texture.
dispose() Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app.
forceContextLoss() Simulates a loss of the WebGL context. This requires support for the WEBGL_lose_context extension.
forceContextRestore() Simulates a restore of the WebGL context. This requires support for the WEBGL_lose_context extension.
getActiveCubeFace(): number Returns the active cube face.
getActiveMipmapLevel(): number Returns the active mipmap level.
`getClearAlpha(): number Returns the clear alpha. Ranges within [0,1].
getClearColor(target: Color): Color Returns the clear color.
getContext(): WebGL2RenderingContext Returns the rendering context.
getContextAttributes(): WebGLContextAttributes Returns the rendering context attributes.
getCurrentViewport(target: Vector2): Vector2 Returns the current viewport definition.
getDrawingBufferSize(target: Vector2): Vector2 Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
getPixelRatio(): number Returns the pixel ratio.
getRenderTarget(): WebGLRenderTarget Returns the active render target.
getScissor(target: Vector4): Vector4 Returns the scissor region.
getScissorTest(): boolean Returns true if the scissor test is enabled.
getSize(target: Vector2): Vector2 Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
getViewport(target: Vector4): Vector4 Returns the viewport definition.
initRenderTarget(target: WebGLRenderTarget) Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data can be copied into it using WebGLRenderer.copyTextureToTexture before it has been rendered to.
initTexture(texture: Texture) Initializes the given texture. Useful for preloading a texture rather than waiting until first render (which can cause noticeable lags due to decode and GPU upload overhead).
readRenderTargetPixels(renderTarget: WebGLRenderTarget, x: number, y: number, width: number, height: number, buffer: TypedArray, activeCubeFaceIndex: number, textureIndex: number) Reads the pixel data from the given render target into the given buffer.
readRenderTargetPixelsAsync(renderTarget: WebGLRenderTarget, x: number, y: number, width: number, height: number, buffer: TypedArray, activeCubeFaceIndex: number, textureIndex: number): Promise.<TypedArray> (async) Asynchronous, non-blocking version of WebGLRenderer.readRenderTargetPixels.
render(scene: Object3D, camera: Camera) Renders the given scene (or other type of 3D object) using the given camera.
resetState() Can be used to reset the internal WebGL state. This method is mostly relevant for applications which share a single WebGL context across multiple WebGL libraries.
setAnimationLoop(callback: onAnimationCallback) Applications are advised to always define the animation loop with this method and not manually with requestAnimationFrame() for best compatibility.
setClearAlpha(alpha: number) Sets the clear alpha.
setClearColor(color: Color, alpha: number) Sets the clear color and alpha.
setDrawingBufferSize(width: number, height: number, pixelRatio: number) This method allows to define the drawing buffer size by specifying width, height and pixel ratio all at once. The size of the drawing buffer is computed with this formula:
setEffects(effects: Array) Sets the post-processing effects to be applied after rendering.
setNodesHandler(nodesHandler: WebGLNodesHandler) Sets a compatibility node builder for rendering node materials with WebGLRenderer. This enables using TSL (Three.js Shading Language) node materials to prepare for migration to WebGPURenderer.
setOpaqueSort(method: function) Sets a custom opaque sort function for the render lists. Pass null to use the default painterSortStable function.
setPixelRatio(value: number) Sets the given pixel ratio and resizes the canvas if necessary. See also window.devicePixelRatio.
setRenderTarget(renderTarget: WebGLRenderTarget, activeCubeFace: number, activeMipmapLevel: number) Sets the active rendertarget.
setScissor(x: number | Vector4, y: number, width: number, height: number) Sets the scissor region to render from (x, y) to (x + width, y + height).
setScissorTest(boolean: boolean) Enable or disable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions.
setTransparentSort(method: function) Sets a custom transparent sort function for the render lists. Pass null to use the default reversePainterSortStable function.
setViewport(x: number | Vector4, y: number, width: number, height: number) Sets the viewport to render from (x, y) to (x + width, y + height).

domElement

One of the parameters that the constructor of WebGLRenderer accepts is canvas.
If not provided, the canvas is created with createCanvasElement (defined in src/utils.js) which creates a HTMLCanvasElement (i. e. a <canvas>) on which the renderer draws («renders») the scene.
Later in the constructor, canvas is assigned to domElement.
Hence, this domElement, if created by the constructor, must be added to the HTML document:
const container = … // for example: document.createElement('div');
document.body.appendChild(container);
container.appendChild(renderer.domElement);

Animation loop

The callback function that is called after specifying it with setAnimationLoop() generally modifies the scene and then calls renderer.render(scene, camera):
const clock    = new THREE.Clock();
const renderer = new THREE.WebGLRenderer();
const scene    = …
const camera   = …
…
renderer.setAnimationLoop(animate);

function animate() {
   const delta = clock.getDelta();
   const time  = clock.getElapsedTime();

   xyz.rotation.x = time * 0.333;
   xyz.rotation.y = time * 0.500;

   t += delta * 0.5;
   … = Math.sin(t);

   renderer.render(scene, camera);

   stats.update();
}
For on-demand rendering, no animation loop is required. Simply calling renderer.render() is sufficient.
If the camera is controlled by a control, the animation loop will likely have to call controls.update() as well.

Geometry

A geometry stores the vertex data of an object.
With r125, THREE.Geometry was removed and THREE.BufferGeometry was suggested as replacement.

THREE.BufferGeometry

BufferGeometry objects store information (such as vertex positions, face indices, normals, colors, UVs, and any custom attributes) in buffers (typed arrays).
This makes them generally faster than standard Geometries, at the cost of being somewhat harder to work with.
All geometries seem to inherit from BufferGeometry.
BufferGeometry inherits from EventDispatcher (not from Object3D, but has the member property _obj which is an Object3D).
An instance of a THREE.BufferGeometry represents a
  • mesh,
  • line or
  • point geometry
Besides geometrical data like vertex coordinates, an instance also stores attributes such as
  • face indices
  • (vertex?) normals
  • colors
  • UVs
  • custom attributes (which are used to reduce the cost of passing this data to the GPU)
BufferAttribute is a class that is designed to store a BufferGeometry's attributes in an efficient way to pass it to a GPU.

setAttribute

obj.setAttribute('position', …)
obj.setAttribute('color' , …)
obj.setAttribute('normal' , …)
obj.setAttribute('uv' ' , …) ?
obj.setAttribute('tangent' , new BufferAttribute(…))

Inheritance

Classes that inherit from BufferGeometry include
BoxGeometry
BoxLineGeometry From which RoundedBoxGeometry inherits
CircleGeometry
ConvexGeometry
CylinderGeometry (from which ConeGeometry inherits)
DecalGeometry
EdgesGeometry (which in contrast to WireframeGeometry renders hard edges only.
ExtrudeGeometry Creates extruded geometry from a Shape (or Path ?) object. TextGeometry inherits from ExtrudeGeometry.
FullscreenTriangleGeometry
InstancedBufferGeometry From which InstancedPointsGeometry and LineSegmentsGeometry inherit.
LatheGeometry (from which CapsuleGeometry inherits)
ParametricGeometry From which PlaneGeometry (for rectangles), SphereGeometry and TubeGeometry inherit.
PolyhedronGeometry From which DodecahedronGeometry, IcosahedronGeometry, OctahedronGeometry and TetrahedronGeometry inherit.
QuadGeometry
RingGeometry
RollerCoasterGeometry
RollerCoasterLiftersGeometry
RollerCoasterShadowGeometry
ShapeGeometry
SkyGeometry Seen in examples/jsm/misc/RollerCoaster.js
TeapotGeometry
TorusGeometry
TorusKnotGeometry
TreesGeometry
WireframeGeometry (the constructor of which takes another geometry as parameter) Compare with EdgesGeometry.
TODO: InstancedBufferGeometry also inherits from BufferGeometry.
Classes that inherit from PolyhedronGeometry include
  • DodecahedronGeometry
  • IcosahedronGeometry
  • OctahedronGeometry
  • TetrahedronGeometry
WireframeGeometry
Compare with classes that inherit from Material which seem to have an attribute wireframe that can be set to true.

Vertex normals

Vertex normals are used by the shader to
  • determine light reflection
  • assist in applying textures
  • provide information how pixels are lighted, shaded and colored
VertexNormalsHelpers (which inherits from LineSegments) visualizes an object's vertex normals.
See also the BufferGeometry method computeVertexNormal().

Triangles

The shape of a geometry is basically created from triangles
If a triangle is looked at its front side, its vertices appear in counterclockwise order («winding order»).
The .side property of a material specifies which side needs to be drawn and can be set to THREE.FrontSide (the default), THREE.BackSide and THREE.DoubleSide.

Material

A material describes an object's surface properties (so it directly influences how it looks like).
Material inherits from EventDispatcher.
Some materials include
TODO MeshPhysicalMaterial inherits from MeshStandardMaterial, MeshPhysicalNodeMaterial from MeshStandardNodeMaterial, MeshSSSNodeMaterial from MeshPhysicalNodeMaterial, RawShaderMaterial from ShaderMaterial
Remember to add a light if using materials that are affected by light!
Note that setting the emissive property to a color on either a MeshLambertMaterial or a MeshPhongMaterial and setting the color to black (and shininess to 0 for MeshPhongMaterial) ends up looking just like the MeshBasicMaterial

LineBasicMaterial

LineBasicMaterial (which inherits from Material) has the property linewidth but, due to limitations of the OpenGL Core Profile with the WebGL renderer, on most platforms this value will be 1 regardless of the set value.

Shader program

A material seems to be connected with a shader program (see the material's callback onBeforeCompile)

Mesh

A mesh is an object that applies a material to a geometry.
A material and/or a geometry can be used for multiple meshes.
A mesh inherits from Object3D and thus records the following attributes of an object relative to its parent in the scene:
The mesh can then be inserted into a scene (for example scene.add()) and then be moved around
Classes that inherit from Mesh include
LineSegments2 Adds arbitrary line widths and the possibility to change widths to world unit. Line2 extends LineSegments2 and allows to create polylines.
InstancedMesh Used for instanced rendering, i. e. if multiple objects with the same geometry and material but different world transformations (including color?) are placed into a scene. In such scenarios, using InstancedMesh reduces the number of draw calls and thus improves the rendering performance. Compare with BatchedMesh.
BatchedMesh Used to render objects with the same material but different geometries and world coordinates. Compare with InstancedMesh.
HTMLMesh Used to render HTML? See also HTMLTexture
TextureHelper
LightProbeHelper
PointLightHelper
TransformControlsPlane
LensflareMesh
Sky Creates a ready-to-go sky. Based on A Practical Analytic Model for Daylight (aka The Preetham Model), the de facto standard analytic skydome model. First implemented by Simon Wallner.
SkyMesh
MarchingCubes Port of webglsamples.org/blob/blob.html
ShadowMesh A shadow Mesh that follows a shadow-casting Mesh in the scene, but is confined to a single plane
GroundedSkybox A ground-projected skybox ….
InstancedPoints
Water See Alex Vlachos: Water Flow and Kyle Hayward: Animating Water Using Flow Maps
WaterMesh
ReflectorForSSRPass
SkinnedMesh
Wireframe Of which I found nothing in the docs. This object is used in the webgl_lines_fat_wireframe example.
QuadMesh Of which I found nothing in the docs.
MorphAnimMesh Of which I found nothing in the docs or the examples. Apparently, it's deprecated.
MorphBlendMesh
MeshPostProcessingMaterial
VOXMesh
Refractor
Reflector
Note that objects such as MeshStandardMaterial, MeshPhongMaterial, MeshBasicMaterial etc. inherit from Material despite their names.
See also the LOD (Level of Detail) class which shows more or less details of a mesh depending on its distance from the camera.
TODO: InstancedMesh. Is this related to InstancedBufferGeometry?

Text and fonts

TextGeometry

A TextGeometry (found in /examples/jsm/geometries) creates a ExtrudeGeometry from a 3D font (which must first be loaded) and a string.
The 3D font can be loaded with an instance of a FontLoader.
A TextGeometry inherits from ExtrudeGeometry

Constructor

The constructor of a TextGeometry takes a string (the text to be rendered) and some options (of which font one seems to be the crucial one):
const txt  = 'Hello world!'; 

const font = …  // An object that is ultimately created by new Font(...)

const txtGeom = new TextGeometry(txt, {
   font          : font,
   depth         : 0.07,
// height        : …
   size          : 0.34 ,    // Size of the text
   curveSegments : 12   ,    // Number of points on the curves
   bevelEnabled  : false,    // Indicates if bevel is enabled
   bevelThickness: 0.5  ,    // How deep into text the bevel goes
   bevelSize     : 0.01 ,    // How far from text outline (including bevelOffset) is bevel
   bevelOffset   : 1    ,    // How far from text outline (including bevelOffset) is bevel
   bevelSegments : 5    ,    // ???
});

Creating Font objects

A Font object can be created directly with FontLoader or indirectly with TTFLoader

FontLoader

const loader = new FontLoader();
font_path    = '…';

loader.load(font_path, function (font) {                          // Note that the Font object is internally created by FontLoader
   const geometry = new TextGeometry(text, {font: font, … });

   …
});

TTFLoader

const loader = new TTFLoader();
font_path    = '…';

loader.load(font_path, function (data) {
   const font = new Font(data);                                   // Note the explicit construction of a Font object
   const geometry = new TextGeometry(text, {font: font, … });

   …
});
The data object which is passed to the function that is given to load is a JSON object with the following top-level keys:
  • glyphs
  • familyName
  • ascender
  • descender
  • underlinePosition
  • underlineThickness
  • boundingBox
  • resolution
  • original_font_information
Apparently, the data object is constructed by opentype.js.

TODO

Light

Light is the abstract base class for an object that emits light. The class inherits from Object3D.
Some interesting derived classes include:
For most materials to be visible, a light must be added to a scene.

Texture

Texture inherits from EventDispatcher
Classes that inherit from Texture include:
See also the TextureLoader and Source classes.

Creation of textures

A texture can be created from
  • static images
  • HTML 5 canvas elements
  • … ?

Creating a texture from a HTML 5 canvas element:

const canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d')
canvas.width  = …
canvas.height = …
  …
const texture  = new THREE.Texture(canvas)
const material = new THREE.MeshStandardMaterial({ map: texture })
const geometry = new THREE.BoxGeometry(200, 200, 200)
const mesh     = new THREE.Mesh(geometry, material)
scene.add(mesh)
  …
ctx.fillStyle = '#435acd'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.font = '15pt Arial'
…

Texel

The pixels of a texture are referred to as texels.

Curve

Curve is an abstract base class for creating objects that contains methods for interpolation.
Classes for 2D curves that inherit from Curve include:
ArcCurve
CubicBezierCurve Comapre with CubicBezierCurve3
EllipseCurve From which ArcCurve inherits`
LineCurve Compare with LineCurve3
QuadraticBezierCurve Compare with QuadraticBezierCurve3
SplineCurve
Classes for 3D curves that inherit from Curve include:
CatmullRomCurve3 A Centripetal CatmullRom Curve which is useful for avoiding cusps and self-intersections in non-uniform catmull rom curves (See On the Parameterization of Catmull-Rom Curve)
CubicBezierCurve3 Compare with CubicBezierCurve
LineCurve3 Compare with LineCurve
QuadraticBezierCurve3 Compare with QuadraticBezierCurve
Classes of parametric curves that inherit from Curve include:
GrannyKnot
HeartCurve See Wolfram MathWorld
VivianiCurve See Wikipedia
KnotCurve
HelixCurve
TrefoilKnot
TorusKnot Compare with TorusKnotGeometry which inherits from ParametricGeometries.TubeGeometry
CinquefoilKnot
TrefoilPolynomialKnot
FigureEightPolynomialKnot
DecoratedTorusKnot4a See also https://prideout.net/blog/old/blog/index.html@p=44.html https://prideout.net/blog/old/blog/index.html@p=44.html
DecoratedTorusKnot4b
DecoratedTorusKnot5a
DecoratedTorusKnot5c
See also Mesh Generation with Python
Other classes that inherit from Curve include:
CurvePath An array of connected Curve objects. Path inherits from CurvePath.
NURBSCurve Overrides getPoint and getTangent.
TorusKnotCurve

CurvePath

A CurvePath inherits from Curve
A CurvePath is an array of connected Curve objects (stored in the member curves) which retains the API of Curve.

Path

Path is 2D path representation which provides methods for creating paths and contours of 2D shapes similar to the 2D Canvas API.
A Path inherits from CurvePath.

Shape

Shape defines an arbitrary 2d shape plane using paths with optional holes.
This object can be used with ExtrudeGeometry, ShapeGeometry, to get points, or to get triangulated faces.
An array of Shape objects is returned by a FontLoader.
A Shape inherits from Path.

Loader

Classes that inherit from Loader include
AMFLoader
AnimationLoader
AudioLoader
BufferGeometryLoader
BVHLoader reads BVH files and outputs a single Skeleton and an AnimationClip. Compare with MDDLoader
ColladaLoader
CompressedTextureLoader Abstract Base class to block based textures loader (dds, pvr, …). Sub classes have to implement the parse() method which will be used in load(). Such subclasses include DDSLoader, KTXLoader and PVRLoader. Compare with DataTextureLoader.
CubeTextureLoader Internally uses the ImageLoader class.
DataTextureLoader Abstract Base class to load generic binary textures formats. Sub classes have to implement the parse() method which will be used in load(). Such subclasses include TGALoader, EXRLoader, RGBELoader, TIFFLoader and RGBMLoader. Compare with CompressedTextureLoader.
DRACOLoader
FBXLoader Loads an FBX file whose version must be greater or equal to 7.0 and the content in ASCII or binary format greater than or equal to 6400
FileLoader
FontLoader Loads a font in JSON format. The loaded font is returned as an array of Shape objects. Compare with TTFLoader.
GCodeLoader Load gcode files usually used for 3D printing or CNC applications. Gcode files are composed by commands used by machines to create objects.
GLTFLoader Spline interpolation
HDRCubeTextureLoader
IESLoader
ImageBitmapLoader
ImageLoader Internally used by the TextureLoader, CubeTextureLoader and ObjectLoader classes.
KMZLoader
KTX2Loader KTX is a container format for various GPU texture formats. The loader supports Basis Universal GPU textures, which can be quickly transcoded to a wide variety of GPU texture compression formats, as well as some uncompressed DataTexture and Data3DTexture formats. (See KTX, DFD and Basis HDR)
LDrawLoader
LottieLoader
LUT3dlLoader See format spec for .3dl and UASTC HDR Texture Specification v1.0.
LUTImageLoader
LUTCubeLoader Cube LUT Specification, Version 1.0
LWOLoader
MaterialLoader
MaterialXLoader
MD2Loader
MDDLoader MDD is a special binary format that stores a position for every vertex in a model for every frame in an animation. Similar to BVH, it can be used to transfer animation data between different 3D applications or engines. Compare with BVHLoader
MTLLoader Loads a Wavefront .mtl file which specifies materials
NodeLoader
NRRDLoader
ObjectLoader Internally uses the ImageLoader class.
OBJLoader
PCDLoader
PDBLoader
PLYLoader Loads a PLY (Polygon File Format or Standard Triangle Format) ASCII file
Rhino3dmLoader
STLLoader Loads STL ASCII files which are created by Solidworks and other CAD programs. The loader returns a non-indexed buffer geomery.
SVGLoader
TDSLoader
TextureLoader Loads a Texture. Uses ImageLoader internally for loading files.
ThreeMFLoader 3D Manufacturing Format of which this loader supports 3D Models, Object resources (Meshes and Components) and Material Resources (Base Materials). 3MF Materials and Properties Extension are only partially supported
TTFLoader Loads TTF files and converts them into typeface JSON that can be used directly to create THREE.Font objects. Requires opentype.js to be included in the project. Compare with FontLoader.
UltraHDRLoader Ultra HDR, HDR/EXR to UltraHDR converter
USDZLoader
VOXLoader
VRMLLoader
VTKLoader

Color

scene = new THREE.Scene();
scene.background = new THREE.Color(0x2f0b03);

Fog

scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x000000, 250, 1400);

BufferAttribute

Classes that inherit from BufferAttribute wrap typed arrays: the constructor of BufferAttribute expects the first parameter to be a typed parameter.
The derived classes' constructors can be given a regular JavaScript array as these constructors call the parent's constructor with new …Array (see for example the Float16BufferAttribute constructor.
TODO: There is also InstancedBufferAttribute which inherits from BufferAttribute.

Vector…

cameraTarget = new THREE.Vector3( 0, 150, 0 );

Object3D

Object3D is the base class for most objects in three.js. Object3D itself inherits from EventDispatcher.
Every instance of an Object3D object has an associated matrix (Matrix4) which defines the object's transformations: position, rotation and scale.
An object's matrix-transformation is relativ to the object's parent object. The transformation relative to the world can be obtained with obj.matrixWorld.
A Bone is almost identical to a blank Object3D.
All classes that inherit from Object3D have an Object3D.layers property which is an instance of the Layers object.
The Group class is almost identical to Object3D.

Properties and methods

position Type: Vector3
rotation Type: Euler
quaternion Type: Quaternion
scale Type: Vector3
modelViewMatrix Type: Matrix4
normalMatrix Type: Matrix3
layers Type: Layers
visible
castShadow
receiveShadow
frustumCulled
renderObject
animations An array.
userData
applyMatrix()
applyQuaternion()
setRotationFromAxisAngle() Assumes axis is normalized
setRotationFromEuler()
setRotationFromMatrix(m) Assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
setRotationFromQuaternion(q) Assumes q is
rotateOnAxis(axis, angle) Rotate object on axis (which is assumed to be normalized) in object space.
rotateOnWorldAxis(axis, angle) rotate object on axis (which is assumed to be normalized) in world space. The method also assumes the parent not to be rotated.
rotateX(angle), rotateY(angle), rotateZ(angle)
translateOnAxis(axis, distance) Translate object by distance along axis (which is assumed to be normalized) in object space.
translateX(distance), translateY(distance), translateZ(distance)
localToWorld(vector)
worldToLocal(vector)
lookAt(x, y, z) x can be a Vector3 in which case the values of y and z are disregarded. This method does not support objects having non-uniformly-scaled parent(s)
add(object), remove(object)
removeFromParent()
clear()
attach(object) Adds object as a child of this, while maintaining the object's world transform
getObjectById(id), getObjectByName(name), getObjectByProperty(name, value)
getObjectsByProperty(name, value results=[])
getWorldPosition(target)
getWorldQuaternion(target)
getWorldScale(target)
getWorldDirection(target)
raycast(raycaster, intersects) Must be overwritten.
traverse(callback)
traverseVisible(callback)
traverseAncestors(callback)
updateMatrix()
updateMatrixWorld(force)
updateWorldMatrix(updateParents, updateChildren)
toJson(meta)
clone(recursive)
copy(source, recursive=true)
onBeforeShadow()
onAfterShadow()
onBeforeRender()
onAfterRender()

Inheritance

Classes that inherit from Object3D include:
Scene
Camera
Sprite
Group
Points
Line
Mesh
ArrowHelper
Light
LOD LOD = Level of Detail. It shows meshes with more or less geometry based on distance from the camera.
CubeCamera
SpotLightHelper Which displays a cone shaped helper object for a SpotLight.
HemisphereLightHelper
DirectionalLightHelper
CSS3DObject
SVGObject
CSS2DObject
Gyroscope
ViewHelper
LwLight
TransformControlsRoot
TransformControlsGizmo
XRControllerModel
OculusHandPointerModel
OculusHandModel
XRHandModel
XRPlanes
CCDIKHelper
AudioListener Which is related to the AudioListener interface of the Web Audio API.
Audio
Bone
ModelNode

Local and world space

There are two relevant coordinate spaces:
Conversion:
const wPos  = new THREE.Vector3();
const wQuat = new THREE.Quaternion();
const wScal = new THREE.Vector3();

obj.getWorldPosition(wPos);
obj.getWorldQuaternion(wQuat);
obj.getWorldScale(wScal);

const localPos      = new THREE.Vector3(1, 0, 0);
const worldPod      = obj.localToWorld(localPos.clone());
const localPosAgain = obj.worldToLocal(worldPos.clone());

Group

The purpose of Group is to make working with groups of objects syntactically easier.
Group is almost identical to the Object3D class.

Controls

Controls is an abstract base class for control objects.
Control objects control an Object3D, usually a camera.
Controls inherits from EventDispatcher.
Because a Controls object does not inherit from Object3D, it cannot (and needs not) be added to a scene.
The constructor of Controls takes
examples/jsm/controls defines the following classes that inherit from Control:
PointerLockControls The perfect choice for first person 3D games. The implementation is based on the Pointer Lock WebAPI.
ArcballControls Control the camera by a virtual trackball
TransformControls Used to transform objects in 3D space by adapting a similar interaction model of DCC tools like Blender. Unlike other controls, it is not intended to transform the scene's camera.
TrackballControls Similar to OrbitControls, but does not maintain a constant camera up vector.
DragControls Drag and drop interactions
OrbitControls OrbitControls allows the camera to orbit around a center; performs orbiting, dollying (zooming), and panning. Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
FlyControls For arbitrary transformations of the camera in 3D space without any limitations. Keys yaw: A = arrow left: left, D = arrow right: right; R: elevate, F: descend. Roll: Q and E. Pitch: arrow up and arrow down. Zoom: W = left mouse button: forward, S = right mouse button: backward.
FirstPersonControls An alternative implementation of FlyControls
MapControls Looking at a map from a bird's eye perspective. MapControls inherits from OrbitControls, with a specific preset for mouse/touch interaction and disabled screen space panning by default.
In most cases, the animation loop should call controls.update().

EventDispatcher

Classes that inherit from EventDispatcher include
Texture
Material
BufferGeometry
Controls
Node
Object3D
AnimationMixer
UniformsGroup
EditorControls
ElementProxyReceiver
NodeEditor
RenderTarget
WebXRManager
EventDispatcher seems to be copied from this github repository.

Fullscreen: window.resize event

window.addEventListener('resize', onWindowResize);

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
}

Matrix4

Coordinate system / AxesHelper

Three.js uses the right-hand rule.
If the observer looks at the origin from a positive z coordinate and positive x coordinates increase towards the right side, then positive y coordinates increase upwards.
The AxesHelper class draws three lines from the origin to the positive coordinates with the X-axes being red, the Y-axes being green and the Z-axes being blue.
AxesHelper inherits from LineSegments.

GridHelper

GridHelper derives from LineSegments and draws a two-dimensional grid.

src/…

src/core

src/core contains the following files
  • BufferAttribute.js - The BufferAttribute class stores data for an attribute (such as vertex positions, face indices, normals, colors, UVs, and any custom attributes ) associated with a BufferGeometry, which allows for more efficient passing of data to the GPU.
  • BufferGeometry.js
  • Clock.js - Uses performance.now to keep track of time. An alternative to Clock is Timer.
  • EventDispatcher.js
  • GLBufferAttribute.js - A buffer attribute class that does not construct a VBO (Vertex Buffer Object?), but allows to alter an already created VBO. This class does not inherit from BufferAttribute (or any other class).
  • InstancedBufferAttribute.js - The class InstancedBufferAttribute inherits from BufferAttribute
  • InstancedBufferGeometry.js
  • InstancedInterleavedBuffer.js - An instanced version of an InterleavedBuffer (from which it also inherits)
  • InterleavedBuffer.js - The adjective interleaved indicates that multiple attributes, possibly of different types, (e.g., position, normal, uv, color) are packed into a single array buffer.
  • InterleavedBufferAttribute.js
  • Layers.js - See below
  • Object3D.js
  • Raycaster.js
  • RenderTarget.js
  • Uniform.js - Global GLSL variables that are passed to shader programs
  • UniformsGroup.js

Layers

A Layers object assigns an Object3D to 1 or more of 32 layers numbered 0 to 31.
Internally the layers are stored as a bit mask, and by default all Object3D instances are a member of layer 0.
Layers can be used to control visibility: an object must share a layer with a camera to be visible when that camera's view is rendered.
All classes that inherit from Object3D have an Object3D.layers property which is an instance of this class.

Raycaster

The Raycaster class allows to select objects (meshes, lines and/or point etc.) with the mouse.
See also the Ray object

src/math

src/math defines the following classes (which inherit from no other class):
  • Box2.js - an axis-aligned bounding-box in 2D space
  • Box3.js - an axis-aligned bounding-box in 3D space Which is used, for example, to represent certain objects' bounding boxes
  • Color.js
  • ColorManagement.js
  • Cylindrical.js - A point's cylindrical coordinates. Compare with Spherical.
  • Euler.js - Euler angles
  • Frustum.js - Used for cameras
  • Interpolant.js
  • Line3.js - A geometric line segment represented by a start and end point.
  • MathUtils.js
  • Matrix2.js
  • Matrix3.js
  • Matrix4.js
  • Plane.js - A two dimensional surface that extends infinitely in 3d space, represented in Hessian normal form by a unit length normal vector and a constant.
  • Quaternion.js - Quaternion, used in three.js to represent rotations. Using quaternions avoids gimbal locks (which are possible with Euler angles).
  • Ray.js - Used by Raycaster
  • Sphere.js - Which is used, for example, to represent certain objects' bounding spheres
  • Spherical.js - A point in spherical coordinates. Compare with Cylindrical.
  • SphericalHarmonics3.js - See An Efficient Representation for Irradiance Environment Maps and Stupid Spherical Harmonics (SH) Tricks
  • Triangle.js - A geometric triangle as defined by three Vector3 objects which representing its three corner
  • Vector2.js
  • Vector3.js
  • Vector4.js
In addition, the directory also contains the interpolants directory.

Quaternion

In the context of 3D graphics, a unit (or normalized) Quaternion is typically used to represent a rotation about a given axis by a given angle.
Three.js expects quaternions to be normalized, so they're used for rotations.
.setFromUnitVectors(F, T) creates a rotation that turns vector F to vector T.
.setFromAxisAngle(V, Θ)

ComputeBoundingBox, ComputeBoundingSphere

The methods ComputeBoundingBox and ComputeBoundingSphere are provided by the four classes
A bounding box seems to be represented by a Box3 object, a bounding sphere by a Sphere object.

Directly accessing source files in three.js git repository (without building project)

<!doctype html>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

<style> html, body {margin: 0} </style>

<script type="importmap">
  {
    "imports": {
      "three"       : "https://web-server.xyz/path-to-github-repo/three.js/src/Three.js",
      "three-addons": "https://web-server.xyz/path-to-github-repo/three.js/examples/jsm/Addons.js",
      "three-libs/" : "https://web-server.xyz/path-to-github-repo/three.js/examples/jsm/libs/"
    }
  }
</script>

<script type='module' src='index.js?2'></script>
Then, in index.js
import * as THREE from 'three';
import { TrackballControls } from 'three-addons';
import { GUI               } from 'three-libs/lil-gui.module.min.js';

…

console.log(THREE.REVISION);

TODO

Libraries and plugins

Externally developped libraries and plugins are listed on this page.

Line like objects

Line which inherits from Object3D, LineSegments which inherits from Line, LineSegments2 which inherits from Mesh, Line2 which inherits from LineSegments2, LineSegmentsGeometry which inherits from InstancedBufferGeometry
Line3 (a base class)
LineLoop inherits from Line but is rendered with gl.LINE_LOOP instead of gl.LINE_STRIP.
Note: Line, LineSegments2 and Line2 are not mashes. Yet, their constructors take a geometry (a LineGeometry?) and a material (a LineMaterial?) much like the constructor of Mesh`.
Points is similar in this regard.

lil-gui

lil-gui makes a floating panel for controllers on the web.
lil-gui is a drop-in replacement for dat.gui (which is no longer maintained) in most projects.

AnimationMixer

AnimationMixer is a player for animations on a particular object in the scene. When multiple objects in the scene are animated independently, one AnimationMixer may be used for each object.

Backend

The two classes WebGLBackend and WebGPUBackend, which inherit from Backend.

renderer.setClearColor() - scene.background

Compare renderer.setClearColor() with scene.background.

See also

D3.js

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1788521439, '216.73.217.21', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/graphic/three_js/index(1278): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78