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';
// 场景、摄像机、渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 灯光
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 0.5).normalize();
scene.add(directionalLight);
// 阴影
renderer.shadowMap.enabled = true;
directionalLight.castShadow = true;
// 创建地面
const geometry = new THREE.PlaneGeometry(100, 100, 1, 1);
const material = new THREE.MeshLambertMaterial({ color: 0xffffff });
const plane = new THREE.Mesh(geometry, material);
plane.receiveShadow = true;
plane.rotation.x = -Math.PI / 2;
scene.add(plane);
// 创建模型
const loader = new GLTFLoader();
loader.load('path/to/your/gltf/model', function (gltf) {
scene.add(gltf.scene);
}, undefined, function (error) {
console.error(error);
});
// 控制器
const controls = new OrbitControls(camera, renderer.domElement);
// 雾化
const fog = new THREE.Fog(0xffffff, 10, 60);
scene.fog = fog;
// 渲染循环
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
这段代码展示了如何使用Three.js创建一个包含场景、摄像机、渲染器、灯光、阴影、地面、模型、控制器以及雾化的基本3D场景。其中,OrbitControls
用于允许用户通过鼠标滚轮、拖拽来控制相机的旋转和缩放,THREE.Fog
用于给场景添加一层雾化效果。这是一个很好的入门级教程,适合新手学习Three.js的基础。
评论已关闭