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

Three.js场景始终空白,无法创建项目的技术求助

Three.js 场景显示白色及类型声明问题解决方案

一、场景显示白色的核心修复

你的代码存在两个关键问题,导致无法正常渲染黑色场景:

  1. 拼写错误:widnow.innerWidth 应为 window.innerWidth,该错误会导致渲染器尺寸设置失效。
  2. 缺少相机与渲染调用:Three.js 必须依赖相机投射场景内容,且需主动执行渲染方法才能将画面输出到页面。

修改后的 main.js 代码:

import { Scene, WebGLRenderer, PerspectiveCamera } from 'three';
import './style.css';

const scene = new Scene();
// 添加透视相机,设置视角、宽高比、近远裁剪面
const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5; // 调整相机位置,确保能捕捉到场景

const renderer = new WebGLRenderer();
// 修正拼写错误,设置渲染器尺寸
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);

// 执行渲染,将场景和相机传入
renderer.render(scene, camera);

// 可选:添加窗口 resize 监听,实现画面自适应
window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.render(scene, camera);
});

二、类型声明提示问题修复

你已安装 @types/three 但编辑器仍报错,可尝试以下操作:

  • 重启代码编辑器(如VS Code),让类型声明文件被重新识别。
  • 若项目无 tsconfig.json,新建该文件并添加类型配置:
{
  "compilerOptions": {
    "types": ["three"]
  }
}
  • 卸载并重装类型包,确保依赖安装完整:
npm uninstall @types/three
npm install @types/three --save-dev

三、额外检查项

  • 确认 package.json 中 three 和 @types/three 版本一致(你的配置均为 0.160.0,符合要求)。
  • 按 F12 打开浏览器开发者工具,查看 Console 面板是否存在其他运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:26:15