<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';
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);
camera and scene objects are passed to renderer.render() in order to render a scene as viewed from the camera. Scene inherits from Object3D and extends it with some properties of which the most interesting ones are: .background (which is a color, a texture, or a CubeTexture or equirectangular texture for a skybox.
.fog WebGLRenderer or WebGPURenderer (or CanvasRenderer? or others?)) PerspectiveCamera and OrthographicCamera. renderer.render(scene, camera). Frustum object). Objects outside the frustum are not rendered. const camera = new THREE.PerspectiveCamera( 45, // field of view (fov) window.innerWidth / window.innerHeight, // aspect 0.1, 10000 // near, far );
camera.lookAt(new THREE.Vector3(x, y, z));
camera.lookAt(mesh_abc.position);
CameraHelper inherits from LineSegments. CameraHelper object uses line segments to visualize the frustum of a camera. const camHlp = new THREE.CameraHelper(camera); scene.add(camHlp);
camHlp.update();
Sprite objects are planes that always face towards the camera (i. e. they're billboarded). WebGLRenderer renders a scene using a camera. WebGPURenderer class. WebGLRenderer inherits from no other class. 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). |
createCanvasElement (defined in src/utils.js) which creates a HTMLCanvasElement (i. e. a <canvas>) on which the renderer draws («renders») the scene. canvas is assigned to domElement. 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);
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();
}
renderer.render() is sufficient. controls.update() as well. THREE.Geometry was removed and THREE.BufferGeometry was suggested as replacement. BufferGeometry objects store information (such as vertex positions, face indices, normals, colors, UVs, and any custom attributes) in buffers (typed arrays). BufferGeometry. BufferGeometry inherits from EventDispatcher (not from Object3D, but has the member property _obj which is an Object3D). THREE.BufferGeometry represents a BufferAttribute is a class that is designed to store a BufferGeometry's attributes in an efficient way to pass it to a GPU. obj.setAttribute('position', …) | |
obj.setAttribute('color' , …) | |
obj.setAttribute('normal' , …) | |
obj.setAttribute('uv' ' , …) | ? |
obj.setAttribute('tangent' , new BufferAttribute(…)) |
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. |
InstancedBufferGeometry also inherits from BufferGeometry. PolyhedronGeometry include DodecahedronGeometry
IcosahedronGeometry
OctahedronGeometry
TetrahedronGeometry Material which seem to have an attribute wireframe that can be set to true. VertexNormalsHelpers (which inherits from LineSegments) visualizes an object's vertex normals. BufferGeometry method computeVertexNormal(). .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 inherits from EventDispatcher. MeshBasicMaterial (not affected by lights)
MeshStandardMaterial. The two important properties of this matierial are roughness and metalness.
MeshLambertMaterial (Rough-looking surfaces, uses Lambertian Reflectance)
MeshPhongMaterial (More advanced than the Lambert material (light is calculated per pixel rather than per vertex), used for shiny-looking surfaces, is affected by lights). An important property of this material is shininess (0 … 100).
LineBasicMaterial (for wireframe-style geometries)
MeshToonMaterial (Cartoon like objects)
ShadowMaterial (A transparent material that shows shadows cast on it)
MeshDepthMaterial
MeshDistanceMaterial (used internally for implementing shadow mapping)
MeshMatcapMaterial (defined by a MatCap or Lit Sphere texture)
MeshNormalMaterial (normal vectors mapped to (RGB) colors)
PointsMaterial (The default material used by Points)
ShaderMaterial (The material is rendered is a custom shader written in GLSL (which is run on the GPU))
SpriteMaterial (Used by Sprite objects) MeshPhysicalMaterial inherits from MeshStandardMaterial, MeshPhysicalNodeMaterial from MeshStandardNodeMaterial, MeshSSSNodeMaterial from MeshPhysicalNodeMaterial, RawShaderMaterial from ShaderMaterial 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 (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. onBeforeCompile) Object3D and thus records the following attributes of an object relative to its parent in the scene: scene.add()) and then be moved around 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 |
MeshStandardMaterial, MeshPhongMaterial, MeshBasicMaterial etc. inherit from Material despite their names. LOD (Level of Detail) class which shows more or less details of a mesh depending on its distance from the camera. InstancedMesh. Is this related to InstancedBufferGeometry? TextGeometry (found in /examples/jsm/geometries) creates a ExtrudeGeometry from a 3D font (which must first be loaded) and a string. FontLoader. TextGeometry inherits from ExtrudeGeometry 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 , // ???
});
Font object can be created directly with FontLoader or indirectly with TTFLoader 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, … });
…
});
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, … });
…
});
data object which is passed to the function that is given to load is a JSON object with the following top-level keys: data object is constructed by opentype.js. Light is the abstract base class for an object that emits light. The class inherits from Object3D. AmbientLight which illuminates all objects equally and doesn't cast shadows
DirectionalLight, a source that is infinitely far away, typically used to simulate the Sun.
PointLight which emits light equally in all directions (a «light bulb»)
SpotLight (See also the somewhat related SpotLightHelper) Texture inherits from EventDispatcher Texture include: CanvasTexture (Crated from a <canvas> element)
CompressedTexture
CompressedArrayTexture
CubeTexture (Made up of six textures, each for a side of a cube)
Data3DTexture
DataArrayTexture
DataTexture
DepthTexture
FramebufferTexture (can only be used with WebGLRenderer.copyFramebufferToTexture()`).
VideoTexture TextureLoader and Source classes. 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'
…
Curve is an abstract base class for creating objects that contains methods for interpolation. Curve include: ArcCurve | |
CubicBezierCurve | Comapre with CubicBezierCurve3 |
EllipseCurve | From which ArcCurve inherits` |
LineCurve | Compare with LineCurve3 |
QuadraticBezierCurve | Compare with QuadraticBezierCurve3 |
SplineCurve |
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 |
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 |
Curve include: CurvePath | An array of connected Curve objects. Path inherits from CurvePath. |
NURBSCurve | Overrides getPoint and getTangent. |
TorusKnotCurve |
CurvePath inherits from Curve CurvePath is an array of connected Curve objects (stored in the member curves) which retains the API of Curve. Path is 2D path representation which provides methods for creating paths and contours of 2D shapes similar to the 2D Canvas API. Path inherits from CurvePath. Shape defines an arbitrary 2d shape plane using paths with optional holes. ExtrudeGeometry, ShapeGeometry, to get points, or to get triangulated faces. Shape objects is returned by a FontLoader. Shape inherits from Path. 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 |
scene = new THREE.Scene(); scene.background = new THREE.Color(0x2f0b03);
scene = new THREE.Scene(); scene.fog = new THREE.Fog(0x000000, 250, 1400);
BufferAttribute wrap typed arrays: the constructor of BufferAttribute expects the first parameter to be a typed parameter. new …Array (see for example the Float16BufferAttribute constructor. InstancedBufferAttribute which inherits from BufferAttribute. cameraTarget = new THREE.Vector3( 0, 150, 0 );
Object3D is the base class for most objects in three.js. Object3D itself inherits from EventDispatcher. Object3D object has an associated matrix (Matrix4) which defines the object's transformations: position, rotation and scale. obj.matrixWorld. Bone is almost identical to a blank Object3D. Object3D have an Object3D.layers property which is an instance of the Layers object. Group class is almost identical to Object3D. 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() |
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 |
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 is to make working with groups of objects syntactically easier. Group is almost identical to the Object3D class. Controls is an abstract base class for control objects. Object3D, usually a camera. Controls inherits from EventDispatcher. Controls object does not inherit from Object3D, it cannot (and needs not) be added to a scene. 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. |
controls.update(). Texture | |
Material | |
BufferGeometry | |
Controls | |
Node | |
Object3D | |
AnimationMixer | |
UniformsGroup | |
EditorControls | |
ElementProxyReceiver | |
NodeEditor | |
RenderTarget | |
WebXRManager |
window.addEventListener('resize', onWindowResize);
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
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 derives from LineSegments and draws a two-dimensional grid. 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 object assigns an Object3D to 1 or more of 32 layers numbered 0 to 31. 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. Object3D have an Object3D.layers property which is an instance of this class. Raycaster class allows to select objects (meshes, lines and/or point etc.) with the mouse. Ray object 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 interpolants directory. .setFromUnitVectors(F, T) creates a rotation that turns vector F to vector T. .setFromAxisAngle(V, Θ) ComputeBoundingBox and ComputeBoundingSphere are provided by the four classes BufferGeometry
SkinnedMesh
InstancedMesh
BatchedMesh Box3 object, a bounding sphere by a Sphere object. <!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>
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);
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) , 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. 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. WebGLBackend and WebGPUBackend, which inherit from Backend. renderer.setClearColor() with scene.background.