在 Three.js 构建的三维世界里,光照效果对场景的真实感起着至关重要的作用。其中,DirectionalLight作为一种常用的光源类型,能模拟出类似太阳光的平行光照效果,均匀地照亮场景中的物体。接下来,让我们深入探究DirectionalLight API 的使用方法。
引入 Three.js 库
和往常一样,先在 HTML 文件中引入 Three.js 库,通过 CDN 链接实现:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js DirectionalLight Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
</head>
<body>
</body>
</html>
基础场景搭建
搭建一个基础的 Three.js 场景,包含场景(Scene)、相机(Camera)和渲染器(Renderer)。
js
// 创建场景
const scene = new THREE.Scene();
// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// 视野角度75度,宽高比根据窗口计算,近裁剪平面0.1,远裁剪平面1000
camera.position.z = 5;
scene.add(camera);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
添加物体
为了展示DirectionalLight的效果,添加一个简单的物体,这里以正方体为例。
js
// 创建正方体几何体
const geometry = new THREE.BoxGeometry(1, 1, 1);
// 创建基础材质
const material = new THREE.MeshStandardMaterial({ color: 0xffffff });
// 创建正方体网格
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
使用 DirectionalLight
这是核心部分,创建并配置DirectionalLight。
js
// 创建平行光,颜色为白色
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
// 设置平行光的方向,这里的向量表示从(1, 1, 1)指向原点(0, 0, 0)
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
DirectionalLight构造函数的第一个参数是光的颜色,这里使用白色0xffffff;第二个参数是光的强度,取值范围一般是 0(无光)到 1(全强度),这里设置为 1。通过position.set方法设置光源位置,并使用normalize方法归一化方向向量,确保光线方向正确。
渲染场景
编写渲染函数并启动动画循环,使场景实时更新。
js
function animate() {
requestAnimationFrame(animate);
// 可添加物体动画逻辑,这里让正方体旋转
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
在上述代码中,requestAnimationFrame递归调用animate函数,实现流畅的动画效果。正方体在每一帧都会绕 x 轴和 y 轴旋转一定角度,同时渲染器将更新后的场景渲染到屏幕上。
通过对DirectionalLight API 的运用,我们能为场景添加具有方向感的光照,极大地增强场景的真实感。Three.js 还有更多光照类型和丰富功能等待你去探索,希望本文能帮助你在三维场景构建中迈出更坚实的一步。