You need to enable JavaScript to run this app. three.module.js的正确使用方法?本地运行Three.js模块示例失效求参考
优惠活动
大模型
产品
解决方案
定价
更多

three.module.js的正确使用方法?本地运行Three.js模块示例失效求参考

本地Three.js Cube示例运行失败的排查与可运行方案

核心失败原因

  • 材质参数语法错误:原代码中new THREE.MeshBasicMaterial({color: "0x00ff00"})的写法存在格式问题,THREE解析颜色值时,传入0x开头的十六进制数值不能加引号;如果要传字符串格式,需使用#00ff00这类带井号的标准CSS色值格式,错误格式会导致材质渲染异常。
  • 脚本运行协议错误:声明为type="module"的脚本受浏览器同源策略限制,不支持通过file://协议直接加载本地文件资源,直接双击打开HTML文件的操作会触发模块加载拦截,导致脚本完全不执行。
  • 依赖路径校验:需确认项目目录下lib/three.module.js的实际存储路径和import语句的路径完全匹配,没有拼写错误、文件存放层级错误的问题。

修正后的完整可运行代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Three.js Cube Demo</title>
    <style>
        body { margin: 0; overflow: hidden; }
    </style>
</head>
<body>
<script type="module">
    // 确认本地lib路径下存在three.module.js文件
    import * as THREE from "lib/three.module.js";
            
    var camera, scene, renderer;            
    var mesh;
            
    init();         
    animate();
            
    function init() {
        camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);                
        camera.position.z = 400;
        scene = new THREE.Scene();
        
        var geometry = new THREE.BoxBufferGeometry(200, 200, 200);                
        // 修正颜色参数格式
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00}); 
                
        mesh = new THREE.Mesh(geometry, material);                
        scene.add(mesh);
                
        renderer = new THREE.WebGLRenderer({antialias: true});       
        renderer.setPixelRatio(window.devicePixelRatio);              
        renderer.setSize(window.innerWidth, window.innerHeight);      
        document.body.appendChild(renderer.domElement);
                
        window.addEventListener('resize', onWindowResize, false);
    }
            
    function onWindowResize() {
        camera.aspect = window.innerWidth / window.innerHeight;             
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    }
            
    function animate() {
        requestAnimationFrame(animate);
        mesh.rotation.x += 0.005;               
        mesh.rotation.y += 0.01;
        renderer.render(scene, camera);
    }
</script>
</body>
</html>

正确运行方式

  • 将下载的three.module.js文件存放到项目目录的lib文件夹下,保证和import语句的路径完全匹配
  • 在项目根目录启动本地静态服务(可通过VS Code的Live Serve插件、Node.js静态服务工具等任意工具实现)
  • 通过http://开头的本地地址访问页面,不要直接双击打开HTML文件运行
  • 运行时如果仍有异常,可打开浏览器开发者工具的控制台面板,根据明确报错定位问题:出现404提示代表模块路径不匹配,出现跨域拦截提示代表仍在通过file协议访问页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.28 17:06:10