threejs lod模型(threeJs入门 js引入)
一:使用three的前置
1.引入three.js
// 引入three.js import * as THREE from three;2.引入three.js其他扩展库
除了three.js核心库以外 ,在threejs文件包中examples/jsm目录下 ,你还可以看到各种不同功能的扩展库 。
一般来说 ,你项目用到那个扩展库 ,就引入那个 ,用不到就不需要引入 。
// 引入扩展库OrbitControls.js import { OrbitControls } from three/addons/controls/OrbitControls.js; // 引入扩展库GLTFLoader.js import { GLTFLoader } from three/addons/loaders/GLTFLoader.js; // 扩展库引入——旧版本 ,比如122, 新版本路径addons替换了examples/jsm import { OrbitControls } from three/examples/jsm/controls/OrbitControls.js;3.学习环境:.html文件中直接引入threejs
如果不是正式开发Web3D项目 ,只是学习threejs功能 ,完全没必要用webpack或vite搭建一个开发环境。
学习使用的环境 ,只要创建一个.html文件,编写threejs代码 ,最后通过本地静态服务打开.html文件就行 。
4.script标签方式引入three.js
你可以像平时开发web前端项目一样 ,通过script标签把three.js当做一个js库引入你的项目 。
three.js库可以在threejs官方文件包下面的build目录获取到 。
<script src="./build/three.js"></script> //随便输入一个API,测试下是否已经正常引入three.js console.log(THREE.Scene);5.ES6 import方式引入
给script标签设置type=“module ”,也可以在.html文件中使用import方式引入three.js 。
<script type="module"> // 现在浏览器支持ES6语法 ,自然包括import方式引入js文件 import * as THREE from ./build/three.module.js; </script>6.type="importmap"配置路径
学习环境中 ,.html文件引入three.js,最好的方式就是参考threejs官方案例 ,通过配置
下面配置的type="importmap"代码具体写法不用掌握记忆 ,复制粘贴后 ,能修改目录就行 ,你可以去电子书课件或者课件源码中复制 。
<!-- 具体路径配置 ,根据自己文件目录设置 --> <script type="importmap"> { "imports": { "three": "../../../three.js/build/three.module.js" } } </script> <!-- 配置type="importmap",.html文件也能和项目开发环境一样方式引入threejs --> <script type="module"> import * as THREE from three; // 浏览器控制台测试 ,是否引入成功 console.log(THREE.Scene); </script>7.type="importmap"配置——扩展库引入
通过配置
配置addons/等价于examples/jsm/ 。
<script type="importmap"> { "imports": { "three": "./three.js/build/three.module.js", "three/addons/": "./three.js/examples/jsm/" } } </script> <script type="module"> // three/addons/路径之后对应的是three.js官方文件包`/examples/jsm/`中的js库 // 扩展库OrbitControls.js import { OrbitControls } from three/addons/controls/OrbitControls.js; // 扩展库GLTFLoader.js import { GLTFLoader } from three/addons/loaders/GLTFLoader.js; console.log(OrbitControls); console.log(GLTFLoader); </script>二:完整代码展示
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Threejs中文网:www.webgl3d.cn</title> </head> <body> <!-- type="importmap"功能:.html文件中也能和nodejs开发环境中一样方式 ,引入npm安装的js库 --> <script type="importmap"> { "imports": { "three": "../../../three.js/build/three.module.js" } } </script> <script src="./index.js" type="module"> </script> </body> </html>js
// 引入three.js import * as THREE from three; /** * 创建3D场景对象Scene */ const scene = new THREE.Scene(); /** * 创建网格模型 */ //创建一个长方体几何对象Geometry const geometry = new THREE.BoxGeometry(50, 50, 50); //材质对象Material const material = new THREE.MeshBasicMaterial({ color: 0x0000ff, //设置材质颜色 }); const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh //设置网格模型在三维空间中的位置坐标 ,默认是坐标原点 mesh.position.set(0,10,0); scene.add(mesh); //网格模型添加到场景中 // console.log(三维场景,scene);创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!