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

求助:Three.js入门代码无法渲染场景问题排查

Three.js 场景无法渲染问题排查

我正在学习Three.js,按照官方入门文档编写代码,但场景无法渲染,仅页面标题显示正常。附上index.html与main.js代码,请求帮忙排查问题:

原index.html代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <h1>My first three.js app</h1>
        <style>
            body { 
                margin: 0; 
            }
        </style>
        <script type="importmap">
            {
              "imports": {
                "three": "https://cdn.jsdelivr.net/npm/three@<v0.167.1>/build/three.module.js",
                "three/addons/": "https://cdn.jsdelivr.net/npm/three@<v0.167.1>/examples/jsm/"
              }
            }
          </script>
    </head>
    <body>
        <script  type="module" src="/main.js"></script>
    </body>
</html>

原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();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

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() {
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render( scene, camera );
}
renderer.setAnimationLoop( animate );

问题排查与修复

  • 核心问题:importmap 版本号格式错误
    importmap里Three.js的CDN链接包含多余的尖括号 <>(three@<v0.167.1>),这会导致浏览器无法正确解析并加载Three.js模块,main.js代码因此无法执行,场景自然无法渲染。

  • 次要规范问题
    <h1>标签被放在了<head>标签内,虽然多数浏览器会容错处理,但按照HTML规范,页面内容标签应放在<body>中。

修正后的index.html代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            body { 
                margin: 0; 
            }
        </style>
        <script type="importmap">
            {
              "imports": {
                "three": "https://cdn.jsdelivr.net/npm/three@0.167.1/build/three.module.js",
                "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.167.1/examples/jsm/"
              }
            }
          </script>
    </head>
    <body>
        <h1>My first three.js app</h1>
        <script type="module" src="/main.js"></script>
    </body>
</html>

修正后,浏览器能正常加载Three.js模块,main.js代码会执行,场景就能正常渲染出旋转的绿色立方体了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:12:40