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

Three.js技术问题:使用Vite时场景为何全黑?

Three.js场景全黑问题修复方案
  • 核心错误:点光源位置设置写法错误
    代码中light.position.set = (0, 10, 10)是错误用法,position.set()是Three.js的方法,需要通过调用形式设置坐标,而非直接赋值。这会导致点光源停留在默认的(0,0,0)位置,与球体重叠,无法有效照亮物体,最终场景呈现全黑。

  • 修复后的完整代码

import * as THREE from 'three'

// Scene
const scene = new THREE.Scene()

// 创建球体
const geometry = new THREE.SphereGeometry(3, 64, 64)
const material = new THREE.MeshStandardMaterial({
    color: "#00ff83",
})
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh);

// 光源
const light = new THREE.PointLight(0xffffff, 1, 100)
// 修正:调用set方法设置光源位置
light.position.set(0, 10, 10)
scene.add(light)

// 相机
const camera = new THREE.PerspectiveCamera(45, 800 / 600)
camera.position.z = 20
scene.add(camera)

// 渲染器
const canvas = document.querySelector(".webgl")
const renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(800, 600)
renderer.render(scene, camera)
  • 额外调试建议
    • 可给场景添加背景色,便于观察渲染状态:scene.background = new THREE.Color(0xf0f0f0)
    • 添加坐标系辅助工具,直观查看物体位置:const axesHelper = new THREE.AxesHelper(10); scene.add(axesHelper)

内容的提问来源于stack exchange,提问作者Luca P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:23:20