我正在尝试使用 XHR 加载钢琴的 GLTF 模型,并在网页上显示加载百分比。该模型是使用 Three.js 库加载的。当我在本地服务器上运行代码时,加载百分比显示正确,并且模型渲染没有任何问题。但是,当我在网站上托管代码时,加载百分比显示为“Infinity%”。我在控制台中收到错误“未捕获的类型错误:无法在“HTMLProgressElement”上设置“值”属性:提供的双精度值是非有限的”。我尝试通过更改代码来调试问题,但无法找出导致问题的原因。我需要帮助来理解为什么会发生这种情况以及如何解决它。
这是代码(我用箭头突出显示了该行(我添加了 parseInt 并将其更改为 NaN%,因此它没有任何用处)):
loader.load(
"models/piano/piano.gltf",
(gltf) => {
piano = gltf.scene;
scene.add(piano);
piano.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
if (child.material.map) {
child.material.map.anisotropy = 4;
}
if (child.material.roughness) {
child.material.roughness = 0.2;
}
if (child.name.startsWith("key")) {
child.userData = {
position: child.position.y,
rotation: child.rotation.x,
};
pianoKeys.push(child);
}
}
});
Promise.all(
notes.map((note, index) => {
loadingProgress.value = parseInt((index / 88) * 100);
currentFile.innerHTML = `sounds/${note}.mp3<span>${
index + 1
} / 88</span>`;
if (index + 1 == 88) {
currentFile.innerHTML = `Finishing loading...`;
}
return new Promise((resolve) => {
audioSources[note] = new Howl({
src: [`sounds/${note}.mp3`],
volume: 1,
onload: resolve,
});
});
})
).then(() => {
filesLoaded();
});
},
(xhr) => {
const percentComplete = parseInt((xhr.loaded / xhr.total) * 100);
currentFile.innerHTML = `models/piano/piano.gltf<span>${percentComplete}%</div>`; // <--
loadingProgress.value = percentComplete;
}
);
好吧,我想我找到了一个解决方案。
将模型文件的大小(以字节为单位)分配给一个变量(在我的例子中为 289907),并使用该变量来计算百分比而不是
xhr.total
,因为 xhr.total
返回 0
效果非常好。
来自文档
onProgress:加载过程中调用的函数。参数将是 XMLHttpRequest 实例,其中包含 .total 和 .loaded 字节。如果服务器没有设置Content-Length头; .总数将为0。
您的服务器似乎没有设置适当的标头,因此您得到:
xhr.loaded / 0 = infinity