Threejs textureLoader - 缩放和映射到网格

Threejs textureLoader - scaling and mapping to mesh

我有一个立方体,我正在尝试将图像映射到该立方体上。我正在使用加载管理器加载图像。我想知道为什么 material.map 以未定义的形式返回,还想知道我是否有缩放问题。原始图像为 512x512。盒子是 20x20x20.

我省略了所有关于相机、渲染器等的代码,但我试图将它们全部包含在下面的代码 snippet/interactive 部分中。

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 函数的回调外部关联 material 这一事实有关,您必须在回调内部执行此操作。

来自 TextureLoader 的文档:

  • 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);