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

Three.js开发时页面无法显示3D对象,求排查代码错误

代码存在的核心问题

  • 拼写错误:PerspectiveCamera 参数中使用了不存在的 window.ineerWidth 属性,正确拼写为 window.innerWidth,该错误会直接抛出JS异常,阻塞后续所有代码执行,导致模型添加、动画循环逻辑都不会运行,是3D对象无法显示的核心原因。
  • 初始渲染时机错误:你在把 torus 模型添加到场景之前就执行了第一次 renderer.render(scene, camera),不过该问题影响不大,因为后续的动画循环会持续刷新渲染结果。
  • CSS 布局问题:canvas 设置了 top:200px 且没有限制高度,你在JS中已经把渲染尺寸设为窗口全高,会导致canvas下半部分超出视口,可能无法看见完整模型。

修复后的完整代码

JS代码

// Main js for Three.js seciton work
import * as THREE from "https://cdn.skypack.dev/three";

const scene = new THREE.Scene();

// 修正拼写错误
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer({
  canvas: document.querySelector('#bg'),
});

renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
camera.position.setZ(30);

const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 )
const material = new THREE.MeshBasicMaterial( { color: 0xFF6347 } );
const torus = new THREE.Mesh( geometry, material );

scene.add(torus)

function animate() {
  requestAnimationFrame( animate );
  renderer.render( scene, camera );
}

animate()

可选CSS调整(适配全屏显示)

canvas {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100vh;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:12:06