name: threejs-lighting
description: Three.js lighting - light types, shadows, environment lighting. Use when adding lights, configuring shadows, setting up IBL, or optimizing lighting performance.
risk: critical
source: community
Three.js 光照
何时使用
- 您需要在 Three.js 场景中添加或调整光照。
- 任务涉及灯光类型、阴影、环境光照或光照性能权衡。
- 您希望通过 Three.js 光照设置改善场景的可读性、真实感或氛围。
快速入门
import*asTHREEfrom"three";// Basic lighting setupconstambientLight=newTHREE.AmbientLight(0xffffff,0.5);scene.add(ambientLight);constdirectionalLight=newTHREE.DirectionalLight(0xffffff,1);directionalLight.position.set(5,5,5);scene.add(directionalLight);灯光类型概览
| 灯光 | 描述 | 阴影支持 | 开销 |
|---|---|---|---|
| AmbientLight | 各处均匀 | 否 | 极低 |
| HemisphereLight | 天空/地面渐变 | 否 | 极低 |
| DirectionalLight | 平行光线(太阳) | 是 | 低 |
| PointLight | 全方位(灯泡) | 是 | 中 |
| SpotLight | 锥形 | 是 | 中 |
| RectAreaLight | 区域光(窗户) | 否* | 高 |
*RectAreaLight 阴影需要自定义解决方案
AmbientLight(环境光)
均匀照亮所有对象。无方向、无阴影。
// AmbientLight(color, intensity)constambient=newTHREE.AmbientLight(0xffffff,0.5);scene.add(ambient);// Modify at runtimeambient.color.set(0xffffcc);ambient.intensity=0.3;HemisphereLight(半球光)
从天空到地面的颜色渐变。适合户外场景。
// HemisphereLight(skyColor, groundColor, intensity)consthemi=newTHREE.HemisphereLight(0x87ceeb,0x8b4513,0.6);hemi.position.set(0,50,0);scene.add(hemi);// Propertieshemi.color;// Sky colorhemi.groundColor;// Ground colorhemi.intensity;DirectionalLight(方向光)
平行光线。模拟远处的光源(太阳)。
// DirectionalLight(color, intensity)constdirLight=newTHREE.DirectionalLight(0xffffff,1);dirLight.position.set(5,10,5);// Light points at target (default: 0, 0, 0)dirLight.target.position.set(0,0,0);scene.add(dirLight.target);scene.add(dirLight);DirectionalLight 阴影
dirLight.castShadow=true;// Shadow map size (higher = sharper, more expensive)dirLight.shadow.mapSize.width=2048;dirLight.shadow.mapSize.height=2048;// Shadow camera (orthographic)dirLight.shadow.camera.near=0.5;dirLight.shadow.camera.far=50;dirLight.shadow.camera.left=-10;dirLight.shadow.camera.right=10;dirLight.shadow.camera.top=10;dirLight.shadow.camera.bottom=-10;// Shadow softnessdirLight.shadow.radius=4;// Blur radius (PCFSoftShadowMap only)// Shadow bias (fixes shadow acne)dirLight.shadow.bias=-0.0001;dirLight.shadow.normalBias=0.02;// Helper to visualize shadow cameraconsthelper=newTHREE.CameraHelper(dirLight.shadow.camera);scene.add(helper);PointLight(点光源)
从一点向所有方向发光。像灯泡。
// PointLight(color, intensity, distance, decay)constpointLight=newTHREE.PointLight(0xffffff,1,100,2);pointLight.position.set(0,5,0);scene.add(pointLight);// PropertiespointLight.distance;// Maximum range (0 = infinite)pointLight.decay;// Light falloff (physically correct = 2)PointLight 阴影
pointLight.castShadow=true;pointLight.shadow.mapSize.width=1024;pointLight.shadow.mapSize.height=1024;// Shadow camera (perspective - 6 directions for cube map)pointLight.shadow.camera.near=0.5;pointLight.shadow.camera.far=50;pointLight.shadow.bias=-0.005;SpotLight(聚光灯)
锥形光。像手电筒或舞台灯。
// SpotLight(color, intensity, distance, angle, penumbra, decay)constspotLight=newTHREE.SpotLight(0xffffff,1,100,Math.PI/6,0.5,2);spotLight.position.set(0,10,0);// Target (light points at this)spotLight.target.position.set(0,0,0);scene.add(spotLight.target);scene.add(spotLight);// PropertiesspotLight.angle;// Cone angle (radians, max Math.PI/2)spotLight.penumbra;// Soft edge (0-1)spotLight.distance;// RangespotLight.decay;// FalloffSpotLight 阴影
spotLight.castShadow=true;spotLight.shadow.mapSize.width=1024;spotLight.shadow.mapSize.height=1024;// Shadow camera (perspective)spotLight.shadow.camera.near=0.5;spotLight.shadow.camera.far=50;spotLight.shadow.camera.fov=30;spotLight.shadow.bias=-0.0001;// Focus (affects shadow projection)spotLight.shadow.focus=1;RectAreaLight(矩形区域光)
矩形区域光。适合柔和、逼真的光照。
import{RectAreaLightHelper}from"three/examples/jsm/helpers/RectAreaLightHelper.js";import{RectAreaLightUniformsLib}from"three/examples/jsm/lights/RectAreaLightUniformsLib.js";// Must initialize uniforms first (WebGL renderer only)RectAreaLightUniformsLib.init();// RectAreaLight(color, intensity, width, height)constrectLight=newTHREE.RectAreaLight(0xffffff,5,4,2);rectLight.position.set(0,5,0);rectLight.lookAt(0,0,0);scene.add(rectLight);// Helperconsthelper=newRectAreaLightHelper(rectLight);rectLight.add(helper);// Works with MeshStandardMaterial, MeshPhysicalMaterial// r183: Clearcoat on MeshPhysicalMaterial is now properly lit by RectAreaLight// Does not cast shadows natively阴影设置
启用阴影
// 1. Enable on rendererrenderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap;// Shadow map types:// THREE.BasicShadowMap - fastest, low quality// THREE.PCFShadowMap - default, filtered// THREE.PCFSoftShadowMap - softer edges// THREE.VSMShadowMap - variance shadow map// 2. Enable on lightlight.castShadow=true;// 3. Enable on objectsmesh.castShadow=true;mesh.receiveShadow=true;// Ground planefloor.receiveShadow=true;floor.castShadow=false;// Usually false for floors优化阴影
// Tight shadow camera frustumconstd=10;dirLight.shadow.camera.left=-d;dirLight.shadow.camera.right=d;dirLight.shadow.camera.top=d;dirLight.shadow.camera.bottom=-d;dirLight.shadow.camera.near=0.5;dirLight.shadow.camera.far=30;// Fix shadow acnedirLight.shadow.bias=-0.0001;// Depth biasdirLight.shadow.normalBias=0.02;// Bias along normal// Shadow map size (balance quality vs performance)// 512 - low quality// 1024 - medium quality// 2048 - high quality// 4096 - very high quality (expensive)接触阴影(伪阴影、快速)
import{ContactShadows}from"three/examples/jsm/objects/ContactShadows.js";constcontactShadows=newContactShadows({resolution:512,blur:2,opacity:0.5,scale:10,position:[0,0,0],});scene.add(contactShadows);灯光辅助器
import{RectAreaLightHelper}from"three/examples/jsm/helpers/RectAreaLightHelper.js";// DirectionalLight helperconstdirHelper=newTHREE.DirectionalLightHelper(dirLight,5);scene.add(dirHelper);// PointLight helperconstpointHelper=newTHREE.PointLightHelper(pointLight,1);scene.add(pointHelper);// SpotLight helperconstspotHelper=newTHREE.SpotLightHelper(spotLight);scene.add(spotHelper);// Hemisphere helperconsthemiHelper=newTHREE.HemisphereLightHelper(hemiLight,5);scene.add(hemiHelper);// RectAreaLight helperconstrectHelper=newRectAreaLightHelper(rectLight);rectLight.add(rectHelper);// Update helpers when light changesdirHelper.update();spotHelper.update();环境光照(IBL)
使用 HDR 环境贴图的基于图像的光照。
import{RGBELoader}from"three/examples/jsm/loaders/RGBELoader.js";constrgbeLoader=newRGBELoader();rgbeLoader.load("environment.hdr",(texture)=>{texture.mapping=THREE.EquirectangularReflectionMapping;// Set as scene environment (affects all PBR materials)scene.environment=texture;// Optional: also use as backgroundscene.background=texture;scene.backgroundBlurriness=0;// 0-1, blur the backgroundscene.backgroundIntensity=1;});// PMREMGenerator for better reflectionsconstpmremGenerator=newTHREE.PMREMGenerator(renderer);pmremGenerator.compileEquirectangularShader();rgbeLoader.load("environment.hdr",(texture)=>{constenvMap=pmremGenerator.fromEquirectangular(texture).texture;scene.environment=envMap;texture.dispose();pmremGenerator.dispose();});立方体纹理环境
constcubeLoader=newTHREE.CubeTextureLoader();constenvMap=cubeLoader.load(["px.jpg","nx.jpg","py.jpg","ny.jpg","pz.jpg","nz.jpg",]);scene.environment=envMap;scene.background=envMap;光照探针(高级)
捕获空间中某一点的光照,用于环境光。
import{LightProbeGenerator}from"three/examples/jsm/lights/LightProbeGenerator.js";// Generate from cube textureconstlightProbe=newTHREE.LightProbe();scene.add(lightProbe);lightProbe.copy(LightProbeGenerator.fromCubeTexture(cubeTexture));// Or from render targetconstcubeCamera=newTHREE.CubeCamera(0.1,100,newTHREE.WebGLCubeRenderTarget(256),);cubeCamera.update(renderer,scene);lightProbe.copy(LightProbeGenerator.fromCubeRenderTarget(renderer,cubeCamera.renderTarget),);常见光照设置
三点照明
// Key light (main light)constkeyLight=newTHREE.DirectionalLight(0xffffff,1);keyLight.position.set(5,5,5);scene.add(keyLight);// Fill light (softer, opposite side)constfillLight=newTHREE.DirectionalLight(0xffffff,0.5);fillLight.position.set(-5,3,5);scene.add(fillLight);// Back light (rim lighting)constbackLight=newTHREE.DirectionalLight(0xffffff,0.3);backLight.position.set(0,5,-5);scene.add(backLight);// Ambient fillconstambient=newTHREE.AmbientLight(0x404040,0.3);scene.add(ambient);室外日光
// Sunconstsun=newTHREE.DirectionalLight(0xffffcc,1.5);sun.position.set(50,100,50);sun.castShadow=true;scene.add(sun);// Sky ambientconsthemi=newTHREE.HemisphereLight(0x87ceeb,0x8b4513,0.6);scene.add(hemi);室内摄影棚
// Multiple area lightsRectAreaLightUniformsLib.init();constlight1=newTHREE.RectAreaLight(0xffffff,5,2,2);light1.position.set(3,3,3);light1.lookAt(0,0,0);scene.add(light1);constlight2=newTHREE.RectAreaLight(0xffffff,3,2,2);light2.position.set(-3,3,3);light2.lookAt(0,0,0);scene.add(light2);// Ambient fillconstambient=newTHREE.AmbientLight(0x404040,0.2);scene.add(ambient);灯光动画
constclock=newTHREE.Clock();functionanimate(){consttime=clock.getElapsedTime();// Orbit light around scenelight.position.x=Math.cos(time)*5;light.position.z=Math.sin(time)*5;// Pulsing intensitylight.intensity=1+Math.sin(time*2)*0.5;// Color cyclinglight.color.setHSL((time*0.1)%1,1,0.5);// Update helpers if usinglightHelper.update();}性能提示
- 限制灯光数量:每盏灯都会增加着色器复杂度
- 使用烘焙光照:静态场景烘焙到纹理
- 更小的阴影贴图:512-1024 通常足够
- 紧凑的阴影视锥体:只覆盖所需区域
- 禁用未使用的阴影:并非所有灯光都需要阴影
- 使用灯光图层:将对象从特定灯光中排除
// Light layerslight.layers.set(1);// Light only affects layer 1mesh.layers.enable(1);// Mesh is on layer 1otherMesh.layers.disable(1);// Other mesh not affected// Selective shadowsmesh.castShadow=true;mesh.receiveShadow=true;decorMesh.castShadow=false;// Small objects often don't need to cast另请参阅
threejs-materials- 材质的光照响应threejs-textures- 光照贴图和环境贴图threejs-postprocessing- 泛光(Bloom)和其他光照效果
限制
- 仅当任务明确符合上述范围时使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停下来询问澄清。