使用 THREEjs 加载纹理的提升问题

时间:2021-03-02 19:05:40

标签: javascript

我的问题在这段代码中(我会尽我所能解释):

这段代码在 for 循环中。 我从 csv 文件加载图像文件列表并使用 lineBreak 进行解析。 我使用这种技术可以轻松地将图像更新到我的网站。 这一切正常,但我想保留每个图像的纵横比。所以下面的代码用于检查每个图像的宽度和高度,并在加载纹理时使用固定宽度设置每个平面几何的新高度。

texture[i] = new THREE.TextureLoader().load(lineBreak[i],function(tex){
  thumbHeight = Math.ceil( (tex.image.height / tex.image.width) * thumbWidth); //here I calculate the new image/texture/thumbnail height
picH = thumbHeight; }); //both picH and thumbHeight are declared as global variables

// 下面这行代码就是问题所在。它被提升到前一个函数之上,并且 thumbHeight 被初始化为 undefined。如果我把它放在函数中,它不会产生任何结果(没有错误)。在函数内使用 console.log 会显示所有正确的结果,但在函数外,thumbHeight 未定义。

mesh = new THREE.PlaneGeometry(thumbWidth, thumbHeight);

您可能已经猜到我是 Javascript 和 Threejs 的新手,而且您是对的。我正在尝试重新创建我多年前在 Flash actionscript 中创建的网站。 任何想法或建议将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

好的,我想通了。

我需要在 for 循环之前创建平面几何图形,并在我的纹理函数中做一些更多的数学运算,然后缩放网格。如下所列:

texture[i] = new THREE.TextureLoader().load(lineBreak[i], function(tex){ 
     thumbHeight = Math.ceil( (tex.image.height/ tex.image.width) * thumbWidth);
     if(thumbHeight > th){ th = thumbHeight; } picH = thumbHeight;
     let sha = picH/thumbWidth; // turn height pixels to a number that scale can use
     thumb[i].scale.set(1,sha); //scale the mesh 
});