如何修正Three.js中GLTF/GLB格式模型的显示效果?
GLTF/GLB模型显示异常问题
加载GLTF/GLB格式模型时,模型初始完全显示为黑色。查阅资料后多数观点认为是灯光问题,但调整灯光参数对模型无任何影响。通过traverse函数修改模型材质,将emissive设为材质颜色、emissiveMap设为材质贴图后,模型显示有所改善,但仍未达到预期效果:
- 当前效果:模型整体偏暗,色彩饱和度低,细节模糊
- 预期效果:模型色彩明亮通透,细节清晰可见
尝试调整模型颜色与灯光参数均无效,以下是完整实现代码:
1. 导入模块
import {OrbitControls} from "https://cdn.jsdelivr.net/npm/three@0.121.1/examples/jsm/controls/OrbitControls.js"; import "https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/FBXLoader.js"; import "https://cdn.jsdelivr.net/npm/three@0.138.0/examples/js/loaders/GLTFLoader.js";
2. 场景设置
const scene = new THREE.Scene(); scene.background = new THREE.Color(0xffffff);
3. 相机设置
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 2000);
4. 渲染器设置
const renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); document.getElementById('modelContainer').appendChild(renderer.domElement);
5. 控制器设置
const control = new OrbitControls(camera, renderer.domElement); control.enableDamping = true; control.minDistance = 4;
6. 灯光设置
const ambient = new THREE.AmbientLight(0xffffff, 1) scene.add(ambient); let light1 = new THREE.PointLight(0xffffff, 1); light1.position.set(0,450,500); scene.add(light1); let light2 = new THREE.PointLight(0xffffff, 1); light2.position.set(500,100,50); scene.add(light2);
7. 模型加载与动画函数
const models = [ './models/bmw/scene.gltf', ]; let currentModelIndex = 0; function loadModel(modelIndex) { const loader = new THREE.GLTFLoader(); loader.load(models[modelIndex], (gltf) => { gltf.scene.traverse((child) => { if (child.isMesh) { child.material.emissive = child.material.color; child.material.emissiveMap = child.material.map; } }); scene.clear(); scene.add(gltf.scene); gltf.scene.rotation.y = Math.PI * -0.75; }); } document.getElementById('nextModel').addEventListener('click', () => { currentModelIndex = (currentModelIndex + 1) % models.length; loadModel(currentModelIndex); }); camera.position.z = 5; function animate() { window.requestAnimationFrame(animate); control.update(); renderer.render(scene, camera); } loadModel(currentModelIndex); animate();
8. HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Models</title> <style> body { margin: 0; } canvas { display: block; } #buttonContainer { position: absolute; top: 5%; left: 45%; z-index: 1; } </style> </head> <body> <div id="buttonContainer"> <button id="nextModel">Next model</button> </div> <div id="modelContainer"></div> <script src="three.js"></script> <script type="module" src="js/script.js"></script> </body> </html>
内容的提问来源于stack exchange,提问作者Michael Muzicenko
相关产品推荐
相关产品推荐

