本文主要记录了一次通过结合环境光与HDR贴图来实现3D场景的渲染。(Threejs版本 r0.118.0)
- 依赖包的导入
import {
Scene,
PerspectiveCamera,
Color,
WebGLRenderer,
LinearToneMapping,
AmbientLight,
Vector3,
Group,
PMREMGenerator,
UnsignedByteType,
HemisphereLight,
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; // 控制器
import { GLTFLoader, GLTF } from 'three/examples/jsm/loaders/GLTFLoader'; // gltf文件加载
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
- 添加环境光
// this.scene = ...
this.scene.add(new AmbientLight(0xffffff, 1));
const hemiLight = new HemisphereLight(0xffffff, 0x000000, 1);
hemiLight.position.set(0, 100, 0);
this.scene.add(hemiLight);
- 设置WebGLRenderer
// this.threeContainer = document.getElementById(
// 'xxxx'
// ) as HTMLElement;
this.renderer = new WebGLRenderer({ antialias: true, alpha: true });
this.renderer.context.getShaderInfoLog = () => '';
this.renderer.setSize(
this.threeContainer.scrollWidth,
this.threeContainer.scrollHeight
);
this.renderer.setPixelRatio(devicePixelRatio);
this.renderer.toneMapping = LinearToneMapping;
this.renderer.toneMappingExposure = 1; // 曝光系数
- 加载HDR贴图
// import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader';
const pmremGenerator = new PMREMGenerator(this.renderer); // 使用hdr作为背景色
pmremGenerator.compileEquirectangularShader();
const scene = this.scene;
new RGBELoader()
.setDataType(UnsignedByteType)
.load('/env/railway_bridge_02_1k.hdr', function (texture) {
const envMap = pmremGenerator.fromEquirectangular(texture).texture;
// envMap.isPmremTexture = true;
pmremGenerator.dispose();
scene.environment = envMap; // 给场景添加环境光效果
scene.background = envMap; // 给场景添加背景图
});
- 加载GLTF模型
// ...
this.loader = new GLTFLoader();
this.loader.load('/model/haballoon.glb', (obj: GLTF) => {
obj.scene.name = 'haballoon';
obj.scene.scale.set(10, 10, 10);
this.scene.add(obj.scene);
});
- 渲染效果
资源文件参考: - 模型: https://sketchfab.com/3d-models/hot-air-balloon-0ac634b7c45b4269ab6c570283b9617c
- HDRI: https://hdrihaven.com/hdri/?h=railway_bridge_02