Javascript Threejs textureLoader-缩放和映射到网格
我有一个立方体,我正试图将图像映射到它上。我正在用加载管理器加载图像。我想知道为什么material.map返回为未定义,还想知道是否存在缩放问题。原始图像是512x512。这些盒子是20x20x20 我遗漏了所有关于相机、渲染器等的代码,但我试图将其全部包含在下面的代码片段/交互部分中Javascript Threejs textureLoader-缩放和映射到网格,javascript,three.js,loader,texture-mapping,Javascript,Three.js,Loader,Texture Mapping,我有一个立方体,我正试图将图像映射到它上。我正在用加载管理器加载图像。我想知道为什么material.map返回为未定义,还想知道是否存在缩放问题。原始图像是512x512。这些盒子是20x20x20 我遗漏了所有关于相机、渲染器等的代码,但我试图将其全部包含在下面的代码片段/交互部分中 var loadingManager = new THREE.LoadingManager(); loadingManager.onProgress = function (item, loaded, tot
var loadingManager = new THREE.LoadingManager();
loadingManager.onProgress = function (item, loaded, total) {
//Loading percentage
console.log(loaded / total * 100 + '%');
}
//Signify loading done
loadingManager.onLoad = function () {
//Start the animation when the models are done loading
animate();
}
function init() {
//create a loader
var loader2 = new THREE.TextureLoader(loadingManager);
//load the texture, and when it's done, push it into a material
loader2.load("../img/leo.jpg", function (texture) {
//do I need to do this?
texture.wrapS = texture.wrapT = THREE.RepeatWrapping
texture.repeat.set(boxSize, boxSize)
//why is this texture not coming through?
console.log(texture)
//does not work:
material1 = new THREE.MeshBasicMaterial({
map: texture,
side: THREE.DoubleSide
});
})
var geo = new THREE.BoxGeometry(30, 30, 30)
var mat = new THREE.MeshBasicMaterial({
color: 0xb7b7b7
})
mesh = new THREE.Mesh(geo, material1)
scene.add(mesh)
}
// This works, so I know the image path is correct
var img = document.createElement('img');
img.src = '../img/leo.jpg';
document.getElementById('container').appendChild(img);
控制台日志中纹理的值如下:
错误与这样一个事实有关,即您在加载程序的
load
函数的回调外部关联材料,您必须在回调内部进行关联
从以下文件中:
- 加载完成时将调用onLoad
loader2.load("../img/leo.jpg", function(texture) {
texture.wrapS = texture.wrapT = THREE.RepeatWrapping
texture.repeat.set( boxSize,boxSize )
//why is this texture 1 not coming through?
console.log(texture)
//neither of these work:
var geo = new THREE.BoxGeometry(30,30,30);
material1 = new THREE.MeshBasicMaterial({ map: texture,side: THREE.DoubleSide });
var mesh = new THREE.Mesh(geo, material1);
// animation loop
function animate() {
requestAnimationFrame( animate );
render();
// update stats
stats.update();
}
...
});
要使其更具可读性并避免回调噩梦,请执行以下操作:
function myInit(texture) {
...
}
loader2.load("../img/leo.jpg", myInit);
定义
material1
时是否尝试添加断点?那一行的纹理值是多少?当您没有预期的行为时,调试是至关重要的。谢谢@Marcs-我已经添加了控制台日志的屏幕抓图。我添加了一个调试器并检查了它。考虑到材料中的图像为空,您有什么想法吗?不要担心代码片段。如果您需要外部库,则不方便,您也可以将其删除。谢谢@Marcs!是的,我想我的代码太乱了。这完全救了它!我太困了,再次感谢你抽出时间。很高兴帮助@EJW。请记住,在JavaScript中,在加载或访问外部资源时必须考虑回调。