ThreeJS中阴影不显示问题求助
问题排查与修复方案
1. 核心错误修正
- 拼写错误:地面的阴影接收属性写错了,
ground.recieveShadow = true应改为ground.receiveShadow = true(正确拼写是receive) - 语法错误:
scene.add(ground)j末尾多了一个j,会导致后续代码(包括renderer.shadowMap.enabled = true)无法执行,直接删除多余的j即可
2. 方向光阴影范围优化
DirectionalLight默认的阴影相机视锥体范围可能没覆盖到场景物体,需要手动调整参数确保立方体和地面都在阴影相机视野内:
light.shadow.camera.left = -5; light.shadow.camera.right = 5; light.shadow.camera.top = 5; light.shadow.camera.bottom = -5; light.shadow.camera.near = 0.1; light.shadow.camera.far = 10;
修复后的完整代码
<style> body { margin: 0; } </style> <script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js" ></script> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.150.1/build/three.module.js", "three/addons/": "https://unpkg.com/three@0.150.1/examples/jsm/" } } </script> <script type="module"> import * as THREE from 'three' import { OrbitControls } from 'three/addons/controls/OrbitControls.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) renderer.shadowMap.enabled = true document.body.appendChild(renderer.domElement) const controls = new OrbitControls(camera, renderer.domElement) const geometry = new THREE.BoxGeometry(1, 1, 1) const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 }) const cube = new THREE.Mesh(geometry, material) cube.castShadow = true cube.position.y = -1.5 scene.add(cube) const light = new THREE.DirectionalLight(0xffffff, 1) light.castShadow = true light.shadow.camera.left = -5 light.shadow.camera.right = 5 light.shadow.camera.top = 5 light.shadow.camera.bottom = -5 light.shadow.camera.near = 0.1 light.shadow.camera.far = 10 light.position.set(2, 3, 2) scene.add(light) camera.position.z = 5 const gg = new THREE.BoxGeometry(5, 0.5, 10) const gm = new THREE.MeshStandardMaterial({ color: 0x0000ff }) const ground = new THREE.Mesh(gg, gm) ground.receiveShadow = true ground.position.y = -3 scene.add(ground) function animate() { requestAnimationFrame(animate) controls.update() renderer.render(scene, camera) cube.rotation.x += 0.01 cube.rotation.y += 0.01 } animate() </script>
额外优化说明
- 将
renderer.shadowMap.enabled = true移到渲染器初始化后,确保阴影功能提前开启 - 调整立方体位置,让它离地面更近,阴影效果更直观
- 添加
controls.update(),保证轨道控制器交互时画面正常更新
内容的提问来源于stack exchange,提问作者Liman
相关产品推荐
相关产品推荐

