使用Three.js渲染无元素显示问题求助(Vite环境)
Three.js项目启动后页面无元素渲染问题排查
我正在学习Three.js,运行npx vite启动项目后,页面未渲染出任何Three.js元素。以下是我的代码片段,恳请帮忙排查问题:
main.js 代码
import * as THREE from '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.setSize(window.innerWidth, window.innerHeight); const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); const cube = new THREE.Mesh(geometry, material); scene.add(cube); camera.position.z = 5; function animate() { requestAnimationFrame(animate); cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render(scene, camera); } animate();
index.html 代码片段
<section class="hero"> <span id="element" data-aos="fade-down"></span> <div id="bg"></div> </section>
排查方向及解决办法
- DOM元素未加载完成就执行代码:
main.js可能在页面DOM渲染前运行,导致document.querySelector('#bg')获取不到元素。
解决:将代码包裹在DOM加载完成的回调中:document.addEventListener('DOMContentLoaded', () => { // 原main.js所有代码放在这里 }); - 容器元素无尺寸:
#bg是普通div,默认没有宽高样式,即使Three.js渲染内容也无法显示。
解决:给#bg添加CSS样式,确保它占满可视区域:#bg { width: 100vw; height: 100vh; display: block; position: absolute; top: 0; left: 0; } - 材质与场景对比度问题:
MeshBasicMaterial不响应光照,场景默认黑色背景,绿色立方体可能因视觉对比问题不易察觉。
解决:可以替换为带光照的材质,或给场景添加环境光:// 添加环境光 const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); // 或者更换材质 const material = new THREE.MeshNormalMaterial(); - 窗口大小变化适配问题:初始宽高比可能因窗口调整失效,导致元素被裁剪或拉伸。
解决:添加窗口resize监听,更新相机和渲染器参数:window.addEventListener('resize', () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); });
内容的提问来源于stack exchange,提问作者Aditya Paluskar
相关产品推荐
相关产品推荐

