ThreeJS Loaders 2

ImageBitmapLoader

A loader that converts an image to an ImageBitmap. An ImageBitmap provides an asynchronous and resource-efficient path for preparing textures for WebGL rendering.

ImageBitmapLoader, unlike FileLoader, does not prevent multiple concurrent requests to the same URL.

Texture.flipY and Texture.premultiplyAlpha with ImageBitmap are not supported. ImageBitmap requires these settings during bitmap creation, whereas regular images require them during GPU uploading. The equivalent options must be set via ImageBitmapLoader. instead, use setOptions.

Code Example

// instantiate a loader
const loader = new THREE.ImageBitmapLoader();
// set options if needed
loader.setOptions( { imageOrientation: 'flipY' } );
// load a image resource
loader.load(
          // resource URL
          'textures/skyboxsun25degtest.png',
          // onLoad callback
          function ( imageBitmap ) {
                   const texture = new THREE.CanvasTexture( imageBitmap );
                   const material = new THREE.MeshBasicMaterial( { map: texture } );
          },
          // onProgress callback currently not supported
          undefined,
          // onError callback
          function ( err ) {
                   console.log( 'An error happened' );
          }
);

Constructor

ImageBitmapLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new ImageBitmapLoader.

Properties

See the base Loader class for common properties.

.options : String

An optional object that sets options for the internally used createImageBitmap factory method. Default is undefined.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.

onLoad — Will be called when load completes. The argument will be the loaded image.

onProgress (optional) — This callback function is currently not supported.

onError (optional) — Will be called when load errors.

Begin loading from url and return the image object that will contain the data.

.setOptions ( options : Object ) : this

Sets the options object for createImageBitmap.

ImageLoader

A loader for loading an Image. This is used internally by the CubeTextureLoader, ObjectLoader and TextureLoader.

Code Example

// instantiate a loader
const loader = new THREE.ImageLoader();
// load a image resource
loader.load(
          // resource URL
          'textures/skyboxsun25degtest.png',
                    
          // onLoad callback
          function ( image ) {
                   // use the image, e.g. draw part of it on a canvas
                   const canvas = document.createElement( 'canvas' );
                   const context = canvas.getContext( '2d' );
                   context.drawImage( image, 100, 100 );
          },
          // onProgress callback currently not supported
          undefined,
          // onError callback
          function () {
                   console.error( 'An error happened.' );
          }
);

Please note three.js r84 dropped support for ImageLoader progress events. For an ImageLoader that supports progress events, see this thread.

Examples

WebGL / loader / obj

WebGL / shaders / ocean

Constructor

ImageLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new ImageLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : HTMLImageElement

url — the path or URL to the file. This can also be a Data URI.

onLoad — Will be called when load completes. The argument will be the loaded image.

onProgress (optional) — This callback function is currently not supported.

onError (optional) — Will be called when load errors.

Begin loading from url and return the image object that will contain the data.

Loader

Base class for implementing loaders.

Constructor

Loader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new Loader.

Properties

.crossOrigin : String

The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS. Default is anonymous.

.withCredentials : Boolean

Whether the XMLHttpRequest uses credentials. See .setWithCredentials. Default is false.

.manager : LoadingManager

The loadingManager the loader is using. Default is DefaultLoadingManager.

.path : String

The base path from which the asset will be loaded. Default is the empty string.

.resourcePath : String

The base path from which additional resources like textures will be loaded. Default is the empty string.

.requestHeader : Object

The request header used in HTTP request. See .setRequestHeader. Default is empty object.

Methods

.load () : undefined

This method needs to be implement by all concrete loaders. It holds the logic for loading the asset from the backend.

.loadAsync ( url : String, onProgress : Function ) : Promise

url — A string containing the path/URL of the file to be loaded.

onProgress (optional) — A function to be called while the loading is in progress. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.

This method is equivalent to .load, but returns a Promise.

onLoad is handled by Promise.resolve and onError is handled by Promise.reject.

.parse () : undefined

This method needs to be implement by all concrete loaders. It holds the logic for parsing the asset into three.js entities.

.setCrossOrigin ( crossOrigin : String ) : this

crossOrigin — The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS.

.setWithCredentials ( value : Boolean ) : this

Whether the XMLHttpRequest uses credentials such as cookies, authorization headers or TLS client certificates. See XMLHttpRequest.withCredentials.

Note that this has no effect if you are loading files locally or from the same domain.

.setPath ( path : String ) : this

path — Set the base path for the asset.

.setResourcePath ( resourcePath : String ) : this

resourcePath — Set the base path for dependent resources like textures.

.setRequestHeader ( requestHeader : Object ) : this

requestHeader - key: The name of the header whose value is to be set. value: The value to set as the body of the header.

Set the request header used in HTTP request.

LoaderUtils

An object with several loader utility functions.

Functions

.decodeText ( array : TypedArray ) : String

array — A stream of bytes as a typed array.

The function takes a stream of bytes as input and returns a string representation.

.extractUrlBase ( url : String ) : String

url — The url to extract the base url from.

Extract the base from the URL.

.resolveURL ( url : String, path : String ) : String

url — The absolute or relative url resolve. path — The base path for relative urls to be resolved against.

Resolves relative urls against the given path. Absolute paths, data urls, and blob urls will be returned as is. Invalid urls will return an empty string.

MaterialLoader

A loader for loading a Material in JSON format. This uses the FileLoader internally for loading files.

Code Example

// instantiate a loader
const loader = new THREE.MaterialLoader();
// load a resource
loader.load(
          // resource URL
          'path/to/material.json',
          // onLoad callback
          function ( material ) {
                    object.material = material;
          },
          // onProgress callback
          function ( xhr ) {
                   console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
          },
          // onError callback
          function ( err ) {
                   console.log( 'An error happened' );
          }
);

Constructor

MaterialLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new MaterialLoader.

Properties

See the base Loader class for common properties.

.textures : Object

Object holding any textures used by the material. See .setTextures.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.

onLoad — Will be called when load completes. The argument will be the loaded Material.

onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.

onError (optional) — Will be called when load errors.

Begin loading from url.

.parse ( json : Object ) : Material

json — The json object containing the parameters of the Material.

Parse a JSON structure and create a new Material of the type json.type with parameters defined in the json object.

.setTextures ( textures : Object ) : this

textures — object containing any textures used by the material.

ObjectLoader

A loader for loading a JSON resource in the JSON Object/Scene format.

This uses the FileLoader internally for loading files.

Code Example

const loader = new THREE.ObjectLoader();
loader.load(
          // resource URL
          "models/json/example.json",
          // onLoad callback
          // Here the loaded data is assumed to be an object
          function ( obj ) {
                   // Add the loaded object to the scene
                   scene.add( obj );
          },
          // onProgress callback
          function ( xhr ) {
                   console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
          },
          // onError callback
          function ( err ) {
                   console.error( 'An error happened' );
          }
);
// Alternatively, to parse a previously loaded JSON structure
const object = loader.parse( a_json_object );
scene.add( object );

Constructor

ObjectLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new ObjectLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : undefined

url — the path or URL to the file. This can also be a Data URI.

onLoad — Will be called when load completes. The argument will be the loaded object.

onProgress (optional) — Will be called while load progresses. The argument will be the ProgressEvent instance, which contains .lengthComputable, .total and .loaded. If the server does not set the Content-Length header; .total will be 0.

onError (optional) — Will be called when load errors.

Begin loading from url and call onLoad with the parsed response content.

.parse ( json : Object, onLoad : Function ) : Object3D

json — required. The JSON source to parse.

onLoad — Will be called when parsed completes. The argument will be the parsed object.

Parse a JSON structure and return a threejs object. This is used internally by .load() but can also be used directly to parse a previously loaded JSON structure.

.parseGeometries ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any geometries in the JSON structure.

.parseMaterials ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any materials in the JSON structure using MaterialLoader.

.parseAnimations ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any animations in the JSON structure, using AnimationClip.parse().

.parseImages ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any images in the JSON structure, using ImageLoader.

.parseTextures ( json : Object ) : Object

json — required. The JSON source to parse.

This is used by .parse() to parse any textures in the JSON structure.

.parseObject ( json : Object, geometries : BufferGeometry, materials : Material, animations : AnimationClip ) : Object3D

json — required. The JSON source to parse.

geometries — required. The geometries of the JSON.

materials — required. The materials of the JSON.

animations — required. The animations of the JSON.

This is used by .parse() to parse any 3D objects in the JSON structure.

TextureLoader

Class for loading a texture. This uses the ImageLoader internally for loading files.

Code Example

const texture = new THREE.TextureLoader().load( 'textures/land_ocean_ice_cloud_2048.jpg' );
// immediately use the texture for material creation
const material = new THREE.MeshBasicMaterial( { map: texture } );

Code Example with Callbacks

// instantiate a loader
const loader = new THREE.TextureLoader();
// load a resource
loader.load(
          // resource URL
          'textures/land_ocean_ice_cloud_2048.jpg',
          // onLoad callback
          function ( texture ) {
                   // in this example we create the material when the texture is loaded
                   const material = new THREE.MeshBasicMaterial( {
                             map: texture
                    } );
          },
          // onProgress callback currently not supported
          undefined,
          // onError callback
          function ( err ) {
                   console.error( 'An error happened.' );
          }
);

Please note three.js r84 dropped support for TextureLoader progress events. For a TextureLoader that supports progress events, see this thread.

Examples

geometry / cube

Constructor

TextureLoader( manager : LoadingManager )

manager — The loadingManager for the loader to use. Default is THREE.DefaultLoadingManager.

Creates a new TextureLoader.

Properties

See the base Loader class for common properties.

Methods

See the base Loader class for common methods.

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : Texture

url — the path or URL to the file. This can also be a Data URI.

onLoad (optional) — Will be called when load completes. The argument will be the loaded texture.

onProgress (optional) — This callback function is currently not supported.

onError (optional) — Will be called when load errors.

Begin loading from the given URL and pass the fully loaded texture to onLoad. The method also returns a new texture object which can directly be used for material creation. If you do it this way, the texture may pop up in your scene once the respective loading process is finished.


Related Topics

ThreeJS Layers

A Layers object assigns an Object3D to one or more of the 32 layers numbered 0 to 31 - the layers are internally stored as a bit mask, and all...

1 minute read.

ThreeJS Installation

You can use npm and modern build tools to install three.js, or you can get started quickly with static hosting or a CDN. Installing from npm is the best option...

4 minutes read.

ThreeJS Interpolant

CubicInterpolant Code Example const interpolant = new THREE.CubicInterpolant(new Float32Array( 2 ),new Float32Array( 2 ),1,new Float32Array( 1 ));interpolant.evaluate( 0.5 ); Constructor CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) parameterPositions -- array of positions sampleValues -- array of samples sampleSize...

2 minutes read.

ThreeJS BufferGeometry

A mesh, line, or point geometry representation. Included within buffers are vertex positions, face indices, normals, colours, UVs, and custom attributes, lowering the cost of passing all of this data...

5 minutes read.

ThreeJS AnimationMixer

The AnimationMixer is a player that allows you to play animations on a specific object in the scene. When many items in a scene are animated individually, each object may...

2 minutes read.

ThreeJS AnimationObjectGroup and Utils

AnimationObjectGroup A group of objects that receives a shared animation state. Usage Add items you'd normally send as 'root' to AnimationMixer's function Object() { [native code] } or clipAction method, and instead pass...

2 minutes read.

ThreeJS Lights

Light Abstract base class for lights - all other light types inherit the properties and methods described here. Constructor Light( color : Integer, intensity : Float ) color - (optional) hexadecimal color of the...

10 minutes read.

ThreeJS Audio

It is used to create a non-positional (global ) audio object. Code Example: // create an AudioListener and add it to the camera const listener = new THREE.AudioListener(); camera.add( listener ); // create a global...

6 minutes read.

ThreeJS Matrix Transformations

Three.js encodes 3D transformations using matrices for translations (position), rotations, and scaling. Every Object3D instance has a matrix that records the location, rotation, and scale of the object. This page...

2 minutes read.

ThreeJS Material

Abstract base class for materials. Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use...

6 minutes read.

ThreeJS Property Binding and Mixer

PropertyBinding Internally, this holds a reference to real property in the scene graph. Constructor PropertyBinding( rootNode : Object3D, path, parsedPath ) -- rootNode: -- path -- parsedPath (optional) Properties The properties are as follows: .path : Number.parsedPath...

2 minutes read.

ThreeJS Uniform

Uniforms are global GLSL variables. They are passed to shader programs. Code Example When declaring a uniform of a ShaderMaterial, it is declared by value or by object. uniforms: { time: { value: 1.0...

2 minutes read.

ThreeJS Shadows

LightShadow Serves as a base class for the other shadow classes. Constructor LightShadow( camera : Camera ) camera - the light's view of the world. Create a new LightShadow. This is not intended to be...

7 minutes read.

ThreeJS AnimationAction

AnimationActions are used to schedule the playback of animations saved in AnimationClips. Note that the majority of AnimationAction's methods can be chained together. The "Animation System" page in the "Next Steps" part...

6 minutes read.

ThreeJS Lines and Texts

Drawing Lines Let's say you want to draw a line or a circle, not a wireframe Mesh. First, we need to set up the renderer, scene, and camera. Here is the...

3 minutes read.

ThreeJS Loading 3D Models

There are hundreds of file formats for 3D models, each with its own purpose, set of features, and level of complexity. Although three.js has a lot of loaders, choosing the...

2 minutes read.

ThreeJS Updating Things

If an item has been added to the scene with the specified code, it will immediately update its matrices. const object = new THREE.Object3D(); scene.add( object ); or, if they are the child...

4 minutes read.

ThreeJS Testing with npm

This article explains how to install three.js in a node.js environment so that automated tests may be run. Tests can be done manually or with the help of automated CI...

4 minutes read.

ThreeJS Object3D

This is the base class for most three.js objects, and it provides a set of properties and methods for manipulating objects in 3D space. It should be noted that this can...

9 minutes read.

ThreeJS BufferAttribute

This class stores data for an attribute associated with a BufferGeometry (such as vertex positions, face indices, normals, colours, UVs, and any custom attributes), allowing for more efficient data passing...

4 minutes read.