问题描述
我将GLTF模型(9mb)加载到ThreeJS中。加载速度肯定很慢。在我的PC上加载大约需要4-5秒,在IPhone上加载大约需要11秒。如何加快渲染时间?我的PC和iPhone从ThreeJS网站加载示例的速度比我的项目快。我的项目仅加载了一个对象,因此我觉得它的加载速度应比ThreeJS网站上的示例更快。
我的示例项目位于{@ {3}}
代码
var ourObj;
var ourObj2;
// Instantiate a loader
var loader = new THREE.GLTFLoader();
// Optional: Provide a DRACOLoader instance to decode compressed mesh data
var dracoLoader = new THREE.DRACOLoader();
dracoLoader.setDecoderPath( '/js/draco/' );
loader.setDRACOLoader( dracoLoader );
let scene,camera,renderer,stars,starGeo;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
camera.position.z = 25;
//renderer = new THREE.WebGLRenderer();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor("#000000");
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);
starGeo = new THREE.Geometry();
for(let i=0;i<6000;i++) {
star = new THREE.Vector3(
Math.random() * 600 - 300,Math.random() * 600 - 300,Math.random() * 600 - 300
);
star.velocity = 0;
star.acceleration = 0.02;
starGeo.vertices.push(star);
}
let sprite = new THREE.TextureLoader().load( 'star.png' );
let starMaterial = new THREE.PointsMaterial({
color: 0xaaaaaa,size: 0.7,map: sprite
});
stars = new THREE.Points(starGeo,starMaterial);
scene.add(stars);
// window.addEventListener("resize",onWindowResize,false);
var hemiLight = new THREE.HemisphereLight( 0xffffff,0x444444 );
hemiLight.position.set( 0,300,0 );
scene.add( hemiLight );
var dirLight = new THREE.DirectionalLight( 0xffffff );
dirLight.position.set( 75,-75 );
scene.add( dirLight );
loader.load(
// resource URL
'objs/dracowolf.gltf',// called when the resource is loaded
function ( gltf ) {
scene.add( gltf.scene );
ourObj = gltf.scene;
animate();
},// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth,window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene,camera);
if(ourObj){
ourObj.rotation.y -= .01;
}
starGeo.vertices.forEach(p => {
p.velocity += p.acceleration
p.y -= p.velocity;
if (p.y < -200) {
p.y = 200;
p.velocity = 0;
}
});
starGeo.verticesNeedUpdate = true;
stars.rotation.y +=0.002;
}
init();
解决方法
有关此特定模型的一些建议:
- 使用
.glb
,而不是.gltf
。 glTF的二进制形式将比具有嵌入二进制数据的.gltf
小25-30%,并且不必从数据URI进行解码。也可以将.gltf
与单独的二进制文件.bin
一起使用。使用glTF-Pipeline进行这些更改。 - 在模型开始加载之前,通过调用
dracoLoader.preload()
预加载Draco解码器。在我对您的网页进行的测试中,下载模型后,这将节省500毫秒的时间来获取解码器。 - 考虑使用https://github.com/zeux/meshoptimizer#installing-gltfpack简化模型,或者至少量化模型,然后gzip。这是Draco的替代方法,可能无法很好地压缩文件,但有时可以减少总的加载时间。