Three.js

Three.js

Загрузчики

AnimationLoader

Класс для загрузки анимации в формате JSON. Для загрузки файлов, внутри класса, используется FileLoader.

Пример

// instantiate a loader (создаем экземпляр загрузчика)
var loader = new THREE.AnimationLoader();
// load a resource (загрузка ресурса) loader.load( // resource URL (URL-адрес ресурса) 'animations/animation.js', // Function when resource is loaded // функция, вызываемая при загрузке ресурса function ( animation ) { // do something with the animation // здесь выполняется какая-нибудь анимация }, // Function called when download progresses // функция, вызываемая при процессе загрузки function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Function called when download errors // функция, вызываемая при ошибке загрузки function ( xhr ) { console.log( 'An error happened' ); } );

Конструктор

AnimationLoader( manager )
manager — The loadingManager for the loader to use. По умолчанию это THREE.DefaultLoadingManager.
Создает новый AnimationLoader.

Свойства

.manager
The [page:LoadingManager loadingManager] the loader is using. По умолчанию это [page:DefaultLoadingManager].

Методы

.load( url, onLoad, onProgress, onError )
url — путь или URL к файлу. Также это может быть Data URI.
onLoad — Функция, которая будет вызвана по завершении загрузки. Аргументом будет загруженная анимация.
onProgress — Функция, которая будет вызываться пока идет процесс загрузки. Аргументом будет экземпляр XMLHttpRequest, что содержит байты .total и .loaded.
onError — Функция, которая будет вызвана в случае ошибки при загрузке.
Начинает загрузку с URL-адреса и передает загруженную анимацию функции, указанной в onLoad.

.parse( json, onLoad )
json — обязателен
onLoad — функция, вызываемая по завершении разбора (парсинга) JSON объекта.
Анализирует (разбирает) объект JSON и передает результаты в onLoad. Отдельные клипы объекта будут обработаны с помощью метода AnimationClip.parse.

Исходники


AudioLoader

Класс для загрузки AudioBuffer. Для загрузки файлов, внутри класса, используется FileLoader.

Пример

// instantiate a listener (создаем экземпляр слушателя)
var audioListener = new THREE.AudioListener();
// add the listener to the camera (добавляем слушателя к камере) camera.add( audioListener );
// instantiate audio object (создаем экземпляр аудиообъекта) var oceanAmbientSound = new THREE.Audio( audioListener );
// add the audio object to the scene (добавляем к сцене аудиообъект) scene.add( oceanAmbientSound );
// instantiate a loader (создаем экземпляр загрузчика) var loader = new THREE.AudioLoader();
// load a resource (загружаем ресурс) loader.load( // resource URL (адрес ресурса) 'audio/ambient_ocean.ogg', // Function when resource is loaded // функция, вызываемая после загрузки ресурса function ( audioBuffer ) { // set the audio object buffer to the loaded object // устанавливаем буфер аудиообъекта для загруженного объекта oceanAmbientSound.setBuffer( audioBuffer );
// play the audio - воспроизводим аудио oceanAmbientSound.play(); }, // Function called when download progresses // функция, вызываемая во время выполнения загрузки function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Function called when download errors // функция, вызываемая при ошибках загрузки function ( xhr ) { console.log( 'An error happened' ); } );

Конструктор

AudioLoader( context, manager )
contextAudioContext for the loader to use. Значением по умолчанию является window.AudioContext.
managerloadingManager for the loader to use. По умолчанию это THREE.DefaultLoadingManager.
Создает новый AudioLoader.

Свойства

.manager
The loadingManager the loader is using. По умолчанию это THREE.DefaultLoadingManager.

Методы

load( url, onLoad, onProgress, onError )
url — обязательный аргумент.
onLoad — Будет вызываться при завершении загрузки. Аргументом должен быть загруженный текст ответа.
onProgress — Будет вызываться во время процесса загрузки. Аргументом должен быть экземпляр XmlHttpRequest, который содержит байты .total и .loaded.
onError — будет вызываться в случае ошибок при загрузке.
Начинает загрузку из url и передает загруженный AudioBuffer в onLoad.

Исходники


BufferGeometryLoader

Загрузчик для загрузки BufferGeometry. Для загрузки файлов, внутри класса, используется FileLoader.

Пример

WebGL / geometry / colors / lookuptable
// instantiate a loader
var loader = new THREE.BufferGeometryLoader();
// load a resource loader.load( // resource URL 'models/json/pressure.json', // Function when resource is loaded function ( geometry ) { var material = new THREE.MeshLambertMaterial( { color: 0xF5F5F5 } ); var object = new THREE.Mesh( geometry, material ); scene.add( object ); }, // Function called when download progresses function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Function called when download errors function ( xhr ) { console.log( 'An error happened' ); } );

Конструктор

BufferGeometryLoader( [page:LoadingManager manager] )
[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Creates a new BufferGeometryLoader.

Свойства

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:String url] — required
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:BufferGeometry].
[page:Function onProgress] — Will be called while load progresses. The argument will be the XmlHttpRequest instance, that contain .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and call onLoad with the parsed response content.
[method:BufferGeometry parse]( [page:Object json] )
[page:Object json] — The JSON structure to parse.
Parse a JSON structure and return a [page:BufferGeometry].

Исходники


Cache

Простая система кэширования, используемая внутри FileLoader.

Примеры

WebGL / geometry / text / earcut
WebGL / interactive / instances / gpu
WebGL / loader / ttf

Применение

Чтобы включить кэширование во всех загрузчиках, использующих FileLoader, установите
THREE.Cache.enabled = true

Свойства

.enabled
Свойство определяет, будет ли включено кэширование. Значением по умолчанию является false.
.files
Объект, удерживающий кэшированные файлы. An [page:Object object] that holds cached files.

Методы

.add( key, file )
key — the [page:String key] to reference the cached file by.
[page:Object file] — файл, который нужно кэшировать.
Adds a cache entry with a key to reference the file. If this key already holds a file, it is overwritten.
.get( key )
key — строковый ключ.
Метод получает значение [page:String key]. Если ключа не существует, возвращается значение undefined, т.е. неопределено.
.remove( key )
key — строковый ключ, связанный с кэшированным файлом.
Удаляет кэшированный файл, связанный с данным ключом.
.clear()
Удаляет все значения из кэша.

Исходники


CompressedTextureLoader

Abstract base class for block based textures loader (dds, pvr, ...). This uses the [page:FileLoader] internally for loading files.

Примеры

See the [link:https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/DDSLoader.js DDSLoader] and [link:https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/PVRLoader.js PVRLoader] for examples of derived classes.

Конструктор

CompressedTextureLoader( [page:LoadingManager manager] )

[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Создает новый CompressedTextureLoader.

Свойства

[property:LoadingManager manager]

The [page:LoadingManager loadingManager] the loader is using. Default is [page:DefaultLoadingManager].

[property:String path]

The base path from which files will be loaded. See [page:.setPath]. Default is *undefined*.

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )

[page:String url] — the path or URL to the file. This can also be a [link:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs Data URI].
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded texture.
[page:Function onProgress] — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and pass the loaded texture to onLoad.

[method:FileLoader setPath]( [page:String path] )

Set the base path or URL from which to load files. This can be useful if you are loading many textures from the same directory.

Исходники


CubeTextureLoader

Class for loading a [page:CubeTexture CubeTexture]. This uses the [page:ImageLoader] internally for loading files.

Пример

[example:webgl_materials_cubemap materials / cubemap]
[example:webgl_materials_cubemap_balls_reflection materials / cubemap / balls / reflection]
[example:webgl_materials_cubemap_balls_refraction materials / cubemap / balls / refraction]
[example:webgl_materials_cubemap_dynamic materials / cubemap / dynamic]
[example:webgl_materials_cubemap_dynamic2 materials / cubemap / dynamic2]
[example:webgl_materials_cubemap_refraction materials / cubemap / refraction]
var scene = new THREE.Scene();
scene.background = new THREE.CubeTextureLoader()
	.setPath( 'textures/cubeMaps/' )
	.load( [
				'1.png',
				'2.png',
				'3.png',
				'4.png',
				'5.png',
				'6.png'
			] );

Конструктор

CubeTextureLoader( [page:LoadingManager manager] )

[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].

Создает новый CubeTextureLoader.

Свойства

[property:String crossOrigin]

If set, assigns the [link:https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes crossOrigin] attribute of the image to the value of *crossOrigin*, prior to starting the load. Default is *undefined*.

[property:LoadingManager manager]

The [page:LoadingManager loadingManager] the loader is using. Default is [page:DefaultLoadingManager].

[property:String path]

The base path from which files will be loaded. See [page:.setPath]. Default is *undefined*.

Методы

[method:null load]( [page:String urls], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )

[page:String urls] — array of 6 urls to images, one for each side of the CubeTexture. These can also be [link:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs Data URIs].
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:Texture texture].
[page:Function onProgress] — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and pass the loaded [page:Texture texture] to onLoad.

[method:null setCrossOrigin]( [page:String value] )

Set the [page:.crossOrigin] attribute.

[method:FileLoader setPath]( [page:String path] )

Set the base path or URL from which to load files. This can be useful if you are loading many textures from the same directory.

Исходники


DataTextureLoader

Abstract base class to load generic binary textures formats (rgbe, hdr, ...). This uses the [page:FileLoader] internally for loading files, and creates a new [page:DataTexture].

Примеры

See the [link:https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/RGBELoader.js RGBELoader] for an example of a derived class.

Конструктор

DataTextureLoader( [page:LoadingManager manager] )

[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Создаение нового DataTextureLoader.

Свойства

[property:LoadingManager manager]

The [page:LoadingManager loadingManager] the loader is using. Default is [page:DefaultLoadingManager].

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )

[page:String url] — the path or URL to the file. This can also be a [link:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs Data URI].
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded texture.
[page:Function onProgress] — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and pass the loaded texture to onLoad.

Исходники


FileLoader

A low level class for loading resources with XmlHttpRequest, used internaly by most loaders.

Конструктор

FileLoader( [page:LoadingManager manager] )
[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Creates a new FileLoader.

Свойства

[property:Cache cache]
A [page:Cache cache] instance that hold the response from each request made through this loader, so each file is requested once.
[property:String responseType]
Can be set to change the response type.

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:String url] — required
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded text response.
[page:Function onProgress] — Will be called while load progresses. The argument will be the XmlHttpRequest instance, that contain .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and return the [page:String text] response that will contain the data.
[method:null setCrossOrigin]( [page:String value] )
[page:String value] — The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS.
[method:null setResponseType]( [page:String value] )
[page:String value] — the empty string (default), "arraybuffer", "blob", "document", "json", or "text".

Пример

[example:webgl_morphtargets_human]

Исходники


FontLoader

Class for loading a font in JSON format. Returns a [page:Font Font], which is an array of [page:Shape Shape]s representing the font. This uses the [page:FileLoader] internally for loading files.

You can convert fonts online using [link:https://gero3.github.io/facetype.js/ facetype.js]

Examples

[example:webgl_geometry_text_shapes geometry / text / shapes ]
[example:webgl_geometry_text geometry / text ]
[example:webgl_geometry_text_earcut geometry / text / earcut]
[example:webgl_geometry_text_pnltri geometry / text / pnltri]
var loader = new THREE.FontLoader();
var font = loader.load(
	// resource URL
	'fonts/helvetiker_bold.typeface.json'
	// Function when resource is loaded
	function ( font ) {
		// do something with the font
		scene.add( font );
	},
	// Function called when download progresses
	function ( xhr ) {
		console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
	},
	// Function called when download errors
	function ( xhr ) {
		console.log( 'An error happened' );
	}
);

Constructor

FontLoader( [page:LoadingManager manager] )

[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].

Creates a new FontLoader.

Properties

[property:LoadingManager manager]

The [page:LoadingManager loadingManager] the loader is using. Default is [page:DefaultLoadingManager].

Methods

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )

[page:String url] — the path or URL to the file. This can also be a [link:https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs Data URI].
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:Texture texture].
[page:Function onProgress] — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.

Begin loading from url and pass the loaded [page:Texture texture] to onLoad.

[method:Font parse]( [page:Object json] )

[page:Object json] — The JSON structure to parse.

Parse a JSON structure and return a [page:Font].

Исходники


ImageLoader

Загрузчик для загрузки [page:Image].

Конструктор

ImageLoader( [page:LoadingManager manager] )
[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Создает новый ImageLoader.

Свойства

[property:String crossOrigin]
The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS.

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:String url] — required
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:Image image].
[page:Function onProgress] — Will be called while load progresses. The argument will be the progress event.
[page:Function onError] — Will be called when load errors.
Begin loading from url and return the [page:Image image] object that will contain the data.
[method:null setCrossOrigin]( [page:String value] )
[page:String value] — The crossOrigin string.
The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS.

Пример

// instantiate a loader
var loader = new THREE.ImageLoader();
// load a image resource loader.load( // resource URL 'textures/skyboxsun25degtest.png', // Function when resource is loaded function ( image ) { // do something with it
// like drawing a part of it on a canvas var canvas = document.createElement( 'canvas' ); var context = canvas.getContext( '2d' ); context.drawImage( image, 100, 100 ); }, // Function called when download progresses function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Function called when download errors function ( xhr ) { console.log( 'An error happened' ); } );
[example:webgl_shaders_ocean]

Исходники


JSONLoader

Загрузчик для загрузки объектов в JSON формате.

Конструктор

JSONLoader( [page:LoadingManager manager] )
[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Созадет новый JSONLoader.

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:String url] — required.
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded text response.
[page:Function onProgress] — Will be called while load progresses. The argument will be the XmlHttpRequest instance, that contain .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and pass the JSON to onLoad.
[method:null setTexturePath]( [page:String texturePath] )
[page:String texturePath] — Base path for textures.
Set the base path for textures.
[method:Object3D parse]( [page:Object json], [page:String texturePath] )
[page:String json] — JSON object to parse.
[page:String texturePath] — Base path for textures.
Parse a JSON structure and return an [page:object] containing the parsed [page:Geometry geometry] and [page:Array materials].

Пример

// instantiate a loader
var loader = new THREE.JSONLoader();
// load a resource loader.load( // resource URL 'models/animated/monster/monster.js', // Function when resource is loaded function ( geometry, materials ) { var material = new THREE.MultiMaterial( materials ); var object = new THREE.Mesh( geometry, material ); scene.add( object ); } );
[example:webgl_loader_json_blender]

Исходники


Loader

Base class for implementing loaders.

Конструктор

Loader()
Creates a new Loader. This should be called as base class.

Свойства

[property:Function onLoadStart]
Will be called when load starts.
The default is a function with empty body.
[property:Function onLoadProgress]
Will be called while load progresses.
The default is a function with empty body.
[property:Function onLoadComplete]
Will be called when load completes.
The default is a function with empty body.
[property:string crossOrigin]
The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS.

Методы

[method:Material createMaterial]( [page:object m], [page:string texturePath] )
[page:Object m] — The parameters to create the material.
[page:String texturePath] — The base path of the textures.
Creates the Material based on the parameters m.
[method:Array initMaterials]( [page:Array materials], [page:string texturePath] )
[page:Array materials] — an array of parameters to create materials.
[page:String texturePath] — The base path of the textures.
Creates an array of [page:Material] based on the array of parameters m. The index of the parameters decide the correct index of the materials.
[method:String extractUrlBase]( [page:string url] )
[page:String url] — The url to extract the base url from.
Extract the base from the URL.

Исходники


MaterialLoader

A loader for loading a [page:Material] in JSON format.

Конструктор

MaterialLoader( [page:LoadingManager manager] )
[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Создает новый MaterialLoader.

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:String url] — required
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:Material].
[page:Function onProgress] — Will be called while load progresses. The argument will be the progress event.
[page:Function onError] — Will be called when load errors.
Begin loading from url and return the [page:Material] object that will contain the data.
[method:Material parse]( [page:Object json] )
[page:Object json] — The json object containing the parameters of the Material.
Parse a JSON structure and create a new [page:Material] of the type [page:String json.type] with parameters defined in the json object.

Пример

// instantiate a loader
var loader = new THREE.MaterialLoader();
// load a resource loader.load( // resource URL 'path/to/material.json', // Function when resource is loaded function ( material ) { object.material = material; }, // Function called when download progresses function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Function called when download errors function ( xhr ) { console.log( 'An error happened' ); } );

Source

[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]

ObjectLoader

A loader for loading a JSON resource. Unlike the [page:JSONLoader], this one make use of the .type attributes of objects to map them to their original classes.

Конструктор

ObjectLoader( [page:LoadingManager manager] )
[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Создает новый ObjectLoader.

Свойства

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:String url] — required
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:Object3D object].
[page:Function onProgress] — Will be called while load progresses. The argument will be the XmlHttpRequest instance, that contain .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and call onLoad with the parsed response content.
[method:Object3D parse]( [page:Object json] )
[page:Object json] — required. The JSON source to parse
Parse a JSON content and return a threejs object.
[method:null setCrossOrigin]( [page:String value] )
[page:String value] — The crossOrigin string to implement CORS for loading the url from a different domain that allows CORS.

Пример

// instantiate a loader (создаем экземпляр загрузчика)
var loader = new THREE.ObjectLoader();
// assuming we loaded a JSON structure from elsewhere // предполагаем, что структура JSON загружена из другого места var object = loader.parse( a_json_object );
scene.add( object );
[example:webgl_loader_msgpack]

Исходники

[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]

TextureLoader

Класс для загрузки [page:Texture texture].

Конструктор

TextureLoader( [page:LoadingManager manager] )
[page:LoadingManager manager] — The [page:LoadingManager loadingManager] for the loader to use. Default is [page:LoadingManager THREE.DefaultLoadingManager].
Создает новый TextureLoader.

Свойства

[property:String crossOrigin]
default — *null*.
If set, assigns the *crossOrigin* attribute of the image to the value of *crossOrigin*, prior to starting the load.

Методы

[method:null load]( [page:String url], [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:String url] — required
[page:Function onLoad] — Will be called when load completes. The argument will be the loaded [page:Texture texture].
[page:Function onProgress] — Will be called while load progresses. The argument will be the XmlHttpRequest instance, that contain .[page:Integer total] and .[page:Integer loaded] bytes.
[page:Function onError] — Will be called when load errors.
Begin loading from url and pass the loaded [page:Texture texture] to onLoad.

Пример

// instantiate a loader (создаем экземпляр загрузчика)
var loader = new THREE.TextureLoader();
// load a resource (загружаем ресурс) loader.load( // resource URL (URL-адрес ресурса) 'textures/land_ocean_ice_cloud_2048.jpg', // Function when resource is loaded // функция, вызываемая после загрузки ресурса function ( texture ) { // do something with the texture var material = new THREE.MeshBasicMaterial( { map: texture } ); }, // Function called when download progresses // функция, вызываемая в процессе загрузки function ( xhr ) { console.log( (xhr.loaded / xhr.total * 100) + '% loaded' ); }, // Function called when download errors // функция, вызываемая в случае ошибок загрузки function ( xhr ) { console.log( 'An error happened' ); } );
[example:canvas_geometry_earth]

Исходники

[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]

Менеджеры загрузки

DefaultLoadingManager

A global instance of the [page:LoadingManager LoadingManager], used by most loaders when no custom manager has been specified.
This will be sufficient for most purposes, however there may be times when you desire seperate loading managers for say, textures and models.

Пример

[example:webgl_loader_scene WebGL / loader / scene]
You can optionally set the [page:LoadingManager.onStart onStart], [page:LoadingManager.onLoad onLoad], [page:LoadingManager.onProgress onProgress], [page:LoadingManager.onStart onError] functions for the manager. These will then apply to any loaders using the DefaultLoadingManager.
Note that these shouldn't be confused with the similarly named functions of individual loaders, as they are intended for displaying information about the overall status of loading, rather than dealing with the data that has been loaded.
THREE.DefaultLoadingManager.onStart = function ( url, itemsLoaded, itemsTotal ) {
	console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
THREE.DefaultLoadingManager.onLoad = function ( ) { console.log( 'Loading Complete!'); };
THREE.DefaultLoadingManager.onProgress = function ( url, itemsLoaded, itemsTotal ) { console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' ); };
THREE.DefaultLoadingManager.onError = function ( url ) { console.log( 'There was an error loading ' + url ); };

Свойства

See the [page:LoadingManager LoadingManager] page for details of properties.

Методы

See the [page:LoadingManager LoadingManager] page for details of methods.

Исходники

[link:https://github.com/mrdoob/three.js/blob/master/src/loaders/LoadingManager.js src/loaders/LoadingManager.js]

LoadingManager

Handles and keeps track of loaded and pending data. A default global instance of this class is created and used by loaders if not supplied manually - see [page:DefaultLoadingManager].
In general that should be sufficient, however there are times when it can be useful to have seperate loaders - for example if you want to show seperate loading bars for objects and textures.

Пример

[example:webgl_loader_babylon WebGL / loader / babylon]
[example:webgl_loader_fbx WebGL / loader / fbx]
[example:webgl_loader_obj WebGL / loader / obj]
[example:webgl_materials_reflectivity WebGL / materials / reflectivity]
[example:webgl_postprocessing_outline WebGL / postprocesing / outline]
[example:webgl_terrain_dynamic WebGL / terrain / dynamic]
var manager = new THREE.LoadingManager();
manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
	console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
manager.onLoad = function ( ) { console.log( 'Loading complete!'); };
manager.onProgress = function ( url, itemsLoaded, itemsTotal ) { console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' ); };
manager.onError = function ( url ) { console.log( 'There was an error loading ' + url ); };
var loader = new THREE.OBJLoader( manager ); loader.load( 'file.obj', function ( object ) { // } );

Конструктор

LoadingManager( [page:Function onLoad], [page:Function onProgress], [page:Function onError] )
[page:Function onLoad] — (optional) this function will be called when all loaders are done.
[page:Function onProgress] — (optional) this function will be called when an item is complete.
[page:Function onError] — (optional) this function will be called a loader encounters errors.
Создает новый LoadingManager.

Свойства

[property:Function onStart]
This function will be called when loading starts. The arguments are:
[page:String url] — The url of the item just loaded.
[page:Integer itemsLoaded] — the number of items already loaded so far.
[page:Iteger itemsTotal] — the total amount of items to be loaded.

By default this is undefined.

[property:Function onLoad]

This function will be called when all loading is completed. By default this is undefined, unless passed in the constructor.

[property:Function onProgress]

This function will be called when an item is complete. The arguments are:
[page:String url] — The url of the item just loaded.
[page:Integer itemsLoaded] — the number of items already loaded so far.
[page:Iteger itemsTotal] — the total amount of items to be loaded.

By default this is undefined, unless passed in the constructor.

[property:Function onError]

This function will be called when any item errors, with the argument:
[page:String url] — The url of the item that errored.

By default this is undefined, unless passed in the constructor.

Методы

Note: The following methods are designed to be called internally by loaders. You shouldn't call them directly.

[method:null itemStart]( [page:String url] )

[page:String url] — the url to load

This should be called by any loader used by the manager when the loader starts loading an url.

[method:null itemEnd]( [page:String url] )

[page:String url] — the loaded url

This should be called by any loader used by the manager when the loader ended loading an url.

[method:null itemError]( [page:String url] )

[page:String url] — the loaded url

This should be called by any loader used by the manager when the loader errors loading an url.

Source

[link:https://github.com/mrdoob/three.js/blob/master/src/loaders/LoadingManager.js src/loaders/LoadingManager.js]