按教程编写的Three.js立方体代码无法渲染,显示空白求助
问题排查:Three.js立方体无法渲染的原因及修复
核心问题及修复点:
未使用THREE命名空间调用PerspectiveCamera
全局引入Three.js时,所有核心类都挂载在THREE对象下,直接写new PerspectiveCamera()会导致浏览器报错PerspectiveCamera is not defined,中断代码执行。必须改为new THREE.PerspectiveCamera()。CSS position属性值错误
#threejs-container的position:block是无效属性,改为position:relative(或absolute),确保容器正确占满视口,避免渲染画布布局异常。
修正后的完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Intro to Three JS</title> <style> * { margin:0; padding:0; box-sizing:border-box; font-family: "Poppins", sans-serif; } html, body { height:100vh; width:100vw; overflow: hidden; /* 可选,防止滚动条出现 */ } #threejs-container { position:relative; /* 修正无效的position值 */ width:100%; height:100%; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> </head> <body> <div id="threejs-container"></div> <script> //Sizes const width = window.innerWidth const height = window.innerHeight //Scene const scene = new THREE.Scene() scene.background = new THREE.Color(0x262626) //Camera - 修正:添加THREE命名空间 const camera = new THREE.PerspectiveCamera(45, width/height, 0.1, 100) camera.position.set(0,0,10) //Creating a Cube const geometry = new THREE.BoxGeometry(2,2,2) const material = new THREE.MeshBasicMaterial({ color: 0xffffff, wireframe:true}) const cube = new THREE.Mesh(geometry, material) scene.add(cube) //Renderer const renderer = new THREE.WebGL1Renderer() renderer.setSize(width,height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) //Render the scene const container = document.querySelector('#threejs-container') container.append(renderer.domElement) // 可选:添加动画循环,让立方体旋转(方便验证渲染效果) function animate() { requestAnimationFrame(animate) cube.rotation.x += 0.01 cube.rotation.y += 0.01 renderer.render(scene,camera) } animate() </script> </body> </html>
额外说明:
- 移除了脚本的
type="module"属性,全局引入Three.js无需模块模式,避免潜在作用域问题。 - 添加
overflow: hidden到html和body,防止视口出现滚动条。 - 可选添加动画循环,让立方体持续旋转,直观验证渲染效果。
内容的提问来源于stack exchange,提问作者Skymasta
相关产品推荐
相关产品推荐

