THREE.js 使用 Promises 添加纹理
THREE.js Add textures with Promises
我正在尝试使用承诺在 THREE.JS
中加载纹理,但我不知道该怎么做。我看过它们是如何工作的,但是有什么例子吗?
我正在尝试在立方体网格中加载图片 (img.png
)。
我不想使用 JSON。
这是 THREE.ImageUtils.loadTexture 的源代码来自 THREE.js:
THREE.ImageUtils = {
crossOrigin: undefined,
loadTexture: function ( url, mapping, onLoad, onError ) {
var loader = new THREE.ImageLoader();
loader.crossOrigin = this.crossOrigin;
var texture = new THREE.Texture( undefined, mapping );
loader.load( url, function ( image ) {
texture.image = image;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}, undefined, function ( event ) {
if ( onError ) onError( event );
} );
texture.sourceFile = url;
return texture;
},
所以你可以把它包装在一个自定义函数中,returns 一个 Promise(这是 ES6 语法):
loadTextureAsync (url, mapping) {
return new Promise ((resolve, reject) => {
const onLoad = (texture) => resolve (texture)
const onError = (event) => reject (event)
THREE.ImageUtils.loadTexture(
url, mapping, onLoad, onError)
})
}
我使用 THREE.TextureLoader
并将其包装在这样的 Promise 中:
// Wrapper function that returns a Promise that resolves to a texture instance
function loadTexture(url) {
return new Promise(resolve => {
new THREE.TextureLoader().load(url, resolve)
})
}
// How to use it
loadTexture('myTexture.jpg').then(texture => {
var geometry = new THREE.SphereBufferGeometry(500, 60, 40)
var material = new THREE.MeshBasicMaterial({ map: texture })
sphere = new THREE.Mesh(geometry, material)
scene.add(sphere)
})
我正在尝试使用承诺在 THREE.JS
中加载纹理,但我不知道该怎么做。我看过它们是如何工作的,但是有什么例子吗?
我正在尝试在立方体网格中加载图片 (img.png
)。
我不想使用 JSON。
这是 THREE.ImageUtils.loadTexture 的源代码来自 THREE.js:
THREE.ImageUtils = {
crossOrigin: undefined,
loadTexture: function ( url, mapping, onLoad, onError ) {
var loader = new THREE.ImageLoader();
loader.crossOrigin = this.crossOrigin;
var texture = new THREE.Texture( undefined, mapping );
loader.load( url, function ( image ) {
texture.image = image;
texture.needsUpdate = true;
if ( onLoad ) onLoad( texture );
}, undefined, function ( event ) {
if ( onError ) onError( event );
} );
texture.sourceFile = url;
return texture;
},
所以你可以把它包装在一个自定义函数中,returns 一个 Promise(这是 ES6 语法):
loadTextureAsync (url, mapping) {
return new Promise ((resolve, reject) => {
const onLoad = (texture) => resolve (texture)
const onError = (event) => reject (event)
THREE.ImageUtils.loadTexture(
url, mapping, onLoad, onError)
})
}
我使用 THREE.TextureLoader
并将其包装在这样的 Promise 中:
// Wrapper function that returns a Promise that resolves to a texture instance
function loadTexture(url) {
return new Promise(resolve => {
new THREE.TextureLoader().load(url, resolve)
})
}
// How to use it
loadTexture('myTexture.jpg').then(texture => {
var geometry = new THREE.SphereBufferGeometry(500, 60, 40)
var material = new THREE.MeshBasicMaterial({ map: texture })
sphere = new THREE.Mesh(geometry, material)
scene.add(sphere)
})