You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用GLTFLoader加载的Three.js模型渲染扁平化异常求助

GLTFLoader加载的Three.js模型渲染扁平化异常求助

嘿,我瞅了你的代码,立刻发现几个明显的问题,这些大概率就是模型看起来扁平没层次的原因,咱们一个个来修正:

1. 相机的两个致命错误

你创建PerspectiveCamera的时候参数顺序搞反了,而且相机位置的设置写法完全错了:

  • PerspectiveCamera的参数顺序是:fov, 宽高比(aspect), near, far,你写成了70, innerHeight, innerWidth,这会导致相机的透视完全错乱,模型渲染变形;
  • 你用了camera.position.set = ( 0, 0, 0 );,这是把set方法赋值成了一个无效的表达式,正确的写法是调用方法camera.position.set(x, y, z),而且相机得和模型保持一定距离,不然在原点会贴脸看不到完整模型。

2. 光照设置太简陋

你只加了一个方向光,但没设置光源位置,默认光源在原点和相机、模型挤在一起,等于没给模型打有效光照——没有明暗对比,模型自然看起来扁平像纸片。咱们得给光源挪个位置,最好再加个环境光补暗部。

修正后的完整代码

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

const scene = new THREE.Scene();

// 修正1:相机参数顺序,宽高比改为 window.innerWidth / window.innerHeight
const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000);
// 修正2:正确设置相机位置,和模型拉开距离
camera.position.set(0, 0, 5);

const renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

// 修正3:给方向光设置位置,让光照有角度
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2);
directionalLight.position.set(5, 5, 5);
scene.add(directionalLight);
// 新增:加一个环境光补暗部,避免阴影处全黑
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);

const controls = new OrbitControls( camera, renderer.domElement );

const loader = new GLTFLoader();
loader.load( './scene.glb' , function (gltf) {
  console.log(gltf);
  const model = gltf.scene;
  scene.add( model );
}, function (xhr){
  console.log((xhr.loaded/xhr.total * 100) + "% loaded")
}, function (error){
  console.log('model not loaded', error); // 这里建议把错误对象也打出来,方便排查
}
);

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

额外提醒

Three.js Editor会自动帮你配置好相机、默认灯光和渲染参数,所以模型在编辑器里正常,但自己写代码的时候这些细节很容易漏。如果改完上面的问题还是有扁平感,可以检查下:

  • 模型本身的材质是否是无高光的漫反射材质,这种材质天生层次感弱;
  • 有没有开启渲染器的阴影(如果模型需要阴影的话,要开启renderer.shadowMap.enabled = true,同时给灯光和模型设置阴影属性)。

先试试上面的代码修改,应该能解决大部分问题!

备注:内容来源于stack exchange,提问作者Bernardy Gosal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 07:09:34