gltfLoader 带进度计数器(加载栏)

问题描述 投票:0回答:1

我正在尝试为

gltf
文件设置加载计数器。问题是,我的文件是
gltf
,而不是
glb
,所以我有三个文件(.gltf .bin .jpg)。当我为 gltf 文件设置
onProgress
回调时,它不会处理这些文件(.bin 和 .jpg),因此我在加载开始时得到 100%。如何设置
onProgress
回调来计算所有三个文件?

const gltfLoader = new GLTFLoader();

// Show loader while the glTF is loading
document.getElementById('loader').style.display = 'block';

// Hide loader when done
  function hideLoader() {
    const loaderContainer = document.getElementById('loader');
    loaderContainer.style.display = 'none';
  }

// LOADING ELEMENTS FROM GLTF //
gltfLoader.load('./Model/Model.gltf', function (gltf) {
    scene.add(gltf.scene);
   // Hide the loader when loading completes
   hideLoader();

function (xhr) {
    // Update progress percentage
    const loaderText = document.getElementById('loader-text');
    
    let progress = 0;
    if (xhr.total && xhr.total > 0) {
      progress = Math.round((xhr.loaded / xhr.total) * 100);
    }     
    loaderText.textContent = `${progress}%`;
},
function (error) {
// Handle loading error
console.error('An error occurred while loading the model:', error);
}
);
three.js gltf
1个回答
0
投票

您应该使用

LoadingManager
,因为它处理所有关联文件的进度。

import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.position.z = 1;
camera.position.y = 0.5;

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const loadingManager = new THREE.LoadingManager();

const loaderContainer = document.getElementById("loader");
const loaderText = document.getElementById("loader-text");

loadingManager.onStart = function () {
  loaderContainer.style.display = "flex";
  loaderText.textContent = `Loading... 0%`;
};

loadingManager.onProgress = function (url, itemsLoaded, itemsTotal) {
  const progress = Math.round((itemsLoaded / itemsTotal) * 100);
  loaderText.textContent = `Loading... ${progress}%`;
};

loadingManager.onLoad = function () {
  loaderContainer.style.display = "none";
};

const gltfLoader = new GLTFLoader(loadingManager);

gltfLoader.load("./static/FlightHelmet.gltf", (gltf) => {
  scene.add(gltf.scene);
});

const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 5, 5);
scene.add(light);

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();

沙盒

© www.soinside.com 2019 - 2024. All rights reserved.