有变量变量时声明函数的方法吗?在下面的代码中,我声明了一个名为loadImage的函数,它返回图像的材质。但是,如果此代码运行,则网格和scene.add(网格)的声明将在加载图像之前运行。有没有办法等待变量在其他命令运行之前完成加载?谢谢!为^ U ^
var geometry = new THREE.BoxGeometry(1,1,1);
var materialimg = new THREE.MeshBasicMaterial();
var materialimg = loadImage("test/map.jpg", manager);
var mesh = new THREE.Mesh(geometry, materialimg);
scene.add(mesh);
作为参考,这里是LoadImage函数:
function loadImage(imagePath, loadingManager){
var loader = new THREE.ImageLoader(loadingManager);
//create a texture
var texture = new THREE.Texture();
loader.load(imagePath, function(image){
texture.image = image;
texture.needsUpadte = true;
var material = new THREE.MeshBasicMaterial();
material.map = texture;
return material;
});
}
以下是调用LoadImage的函数的完整函数:
function testImage(){
var manager = new THREE.LoadingManager();
manager.onProgress = function(item, loaded, total){
console.log(item,loaded,total);
}
var geometry = new THREE.BoxGeometry(1,1,1);
var materialimg = new THREE.MeshBasicMaterial();
var materialimg = loadImage("test/map.jpg", manager);
var mesh = new THREE.Mesh(geometry, materialimg);
scene.add(mesh);
}
答案 0 :(得分:1)
你应该使用这样的回调函数:
function loadImage(imagePath, loadingManager){
var loader = new THREE.ImageLoader(loadingManager);
//create a texture
var texture = new THREE.Texture();
loader.load(imagePath, function(image){
texture.image = image;
texture.needsUpdate = true;
});
return new THREE.MeshBasicMaterial({ map: texture, overdraw: true });
}
function testImage(){
var manager = new THREE.LoadingManager();
manager.onProgress = function(item, loaded, total){
console.log(item,loaded,total);
}
var geometry = new THREE.BoxGeometry(1,1,1);
var materialimg = loadImage("test/map.jpg", manager);
var mesh = new THREE.Mesh(geometry, materialimg);
scene.add(mesh);
}
编辑:修改上面的代码。请注意,您不能在回调函数中使用return
,因为它将在其他上下文中执行。