Three.js 实战:开启阴影、灯光旋转与阴影清晰度设置详解

在 Three.js 中,阴影效果是提升真实感的重要手段。本文将从以下三个方面进行系统讲解:

  1. 如何启用阴影

  2. 如何让灯光动态旋转以制造动态阴影

  3. 如何设置阴影的清晰度(shadow map 分辨率)

一、开启阴影的关键步骤

1. 渲染器启用阴影
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true; // ✅ 启用阴影
document.body.appendChild(renderer.domElement);
 2. 灯光开启投射阴影
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 5, 0);
directionalLight.castShadow = true; // ✅ 允许灯光投射阴影
scene.add(directionalLight);
3. 阴影接收者和投射者设置
  • 接收阴影:receiveShadow = true

  • 投射阴影:castShadow = true

const plane = new THREE.Mesh(
  new THREE.PlaneGeometry(10, 10),
  new THREE.MeshStandardMaterial({ color: 0xffffff })
);
plane.rotation.x = -Math.PI / 2;
plane.receiveShadow = true; // ✅ 接收阴影
scene.add(plane);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(2, 2, 2),
  new THREE.MeshStandardMaterial({ color: 0xff0000 })
);
cube.position.set(0, 2, 0);
cube.castShadow = true; // ✅ 投射阴影
scene.add(cube);

二、实现灯光绕场景旋转

 

const pointLight = new THREE.PointLight(0xffffff, 1, 200);
pointLight.position.set(10, 3, 0);
pointLight.castShadow = true;
scene.add(pointLight);

// 小球可视化光源位置(调试用)
const pointLightHelper = new THREE.PointLightHelper(pointLight, 1);
scene.add(pointLightHelper);

// 动画:光源旋转
let angle = 0;
function animate() {
  requestAnimationFrame(animate);
  angle += 0.01;
  pointLight.position.x = 10 * Math.cos(angle);
  pointLight.position.z = 10 * Math.sin(angle);
  renderer.render(scene, camera);
}
animate();

三、控制阴影清晰度(分辨率)

阴影模糊或者锯齿严重的根本原因通常是shadow map 分辨率太低。默认值是 512 × 512,可以手动提升:


directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;

 

四、全部代码



  
    
    
    Three.js Basic Scene
    
  
  
    
    
  

 

 五、总结

项目 方法
开启阴影 renderer.shadowMap.enabled = true
设置投射者/接收者 castShadow / receiveShadow
灯光开启阴影 light.castShadow = true
提升清晰度 shadow.mapSize = 2048 或以上
阴影区域控制 shadow.camera.* 设置投影盒体
动态灯光 设置位置随 Math.cos/sin(angle) 变化
注意:开启阴影的时候注意开启四个参数、开启灯光的时候一般打开灯光辅助以便看到实施灯光的位置

 

你可能感兴趣的:(three.js,javascript,开发语言,ecmascript)