You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Three.js r82版本阴影效果无法正常显示

Three.js r82 阴影不生效的解决办法

嘿,我仔细扒了你的代码,发现阴影没法正常显示的核心问题是平行光(DirectionalLight)的阴影相机视锥体没配置合适范围。

在Three.js里,平行光的阴影相机是正交相机(OrthographicCamera),默认的视锥体范围特别小,根本罩不住你的立方体和平面,阴影自然就渲染不出来了。你已经把阴影相关的基础开关都打开了,但刚好漏掉了这个关键配置。

修复步骤

只需要在你设置directionalLight.shadow.camera.far = 500;之后,加上这段阴影相机视锥体的范围配置就行:

directionalLight.shadow.camera.left = -10;
directionalLight.shadow.camera.right = 10;
directionalLight.shadow.camera.top = 10;
directionalLight.shadow.camera.bottom = -10;

这个范围刚好能覆盖你的10x10平面和上方的立方体,阴影相机就能正确捕捉到阴影区域了。

确认其他正确配置

顺便帮你核对了阴影生效的必要条件,你都已经做到位了:

  • 渲染器开启了renderer.shadowMap.enabled = true,还设置了软阴影类型,没问题
  • 平行光开启了castShadow = true,正确
  • 立方体设置了castShadow = true,平面设置了receiveShadow = true,符合要求
  • 使用的是MeshPhongMaterial(像MeshBasicMaterial这类基础材质不支持阴影),材质选对了

修改后的完整代码

var scene = new THREE.Scene()
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 )
var renderer = new THREE.WebGLRenderer()
camera.position.set(2,2,2)
camera.lookAt(scene.position)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
document.body.appendChild(renderer.domElement)

var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.6 );
directionalLight.position.set( 3, 10, 5 );
directionalLight.castShadow = true
directionalLight.shadowCameraVisible = true;
scene.add( directionalLight );

directionalLight.shadow.mapSize.width = 512; // default
directionalLight.shadow.mapSize.height = 512; // default
directionalLight.shadow.camera.near = 0.1; // default
directionalLight.shadow.camera.far = 500;
// 添加的阴影相机视锥体配置
directionalLight.shadow.camera.left = -10;
directionalLight.shadow.camera.right = 10;
directionalLight.shadow.camera.top = 10;
directionalLight.shadow.camera.bottom = -10;

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshPhongMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
cube.castShadow = true
scene.add( cube );

var planeGeometry = new THREE.PlaneGeometry(10,10,10)
var plane = new THREE.Mesh(planeGeometry, material)
plane.rotateX(-0.5*Math.PI)
plane.position.y = -0.5
plane.receiveShadow = true
scene.add(plane)

var animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate()

这样修改之后,阴影就能正常显示啦~

内容的提问来源于stack exchange,提问作者Jesse Luo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:13:37