// 引入Three.js的相关组件
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
// 定义一个Three.js场景,并设置背景色为黑色
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000);
// 创建相机并设置属性,然后将相机添加到场景中
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 10, 20);
scene.add(camera);
// 创建WebGL渲染器并将其与画布元素关联
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建一个全局的灯光对象,并将其添加到场景中
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// 创建一个平行光源并将其添加到场景中
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.7);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// 创建OrbitControls控件对象,用于操作相机
const controls = new OrbitControls(camera, renderer.domElement);
// 创建GLTFLoader加载器实例,并加载模型
const gltfLoader = new GLTFLoader();
gltfLoader.load('models/scene.gltf', (gltf) => {
scene.add(gltf.scene);
}, undefined, (error) => {
console.error(error);
});
// 创建RGBELoader加载器实例,并加载环境光照HDR图片
const hdrLoader = new RGBELoader();
hdrLoader.load('textures/scene.hdr', (texture) => {
scene.environment = texture;
texture.mapping = THREE.EquirectangularReflectionMapping;
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.render(scene, camera);
}, undefined, (error) => {
console.error(error);
});
// 使用requestAnimationFrame实现渲染循环
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
controls.update(); // 更新控件以反映相机的变化
}
animate();
这段代码示例展示了如何在Three.js中创建一个基础场景,并使用OrbitControls来控制相机的旋转和缩放,同时加载一个GLTF格式的3D模型和环境光照HDR图片。代码简洁,注重教学,并且有详细的中文注释。