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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:55:37