安装threejs
1.浏览器环境
1.1 script标签引入CDN
html
<script src="https://unpkg.com/three/build/three.js"></script>1.2 ES Module引入CDN
注意引入的是 three.module.js文件
html
<script type="module">
import * as THREE from "https://unpkg.com/three/build/three.module.js";
</script>1.2.1 配置importmap
importmap相当于路径映射,配置方式如下,当我们使用 import引入一个库时,可以不用写很长的路径,直接写映射的key就行
html
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three/build/three.module.js",
"key": "path"
}
}
</script>
<script type="module">
import * as THREE from "three";
</script>1.3 下载到本地
下载之后放进项目根目录中,核心库在build目录中
html
<script src="./three/build/three.js"></script>或者使用 es6 module导入,注意是three.module.js文件
html
<script type="module">
import * as THREE from "./three/build/three.module.js";
</script>也可以配置 importmap
html
<script type="importmap">
{
"imports": {
"three": "./three/build/three.module.js",
}
}
</script>
<script type="module">
import * as THREE from "three";
</script>2.框架环境
2.1 安装
shell
npm i three --save2.2 引入核心库
js
import * as THREE from 'three'2.3 引入扩展库
除了three.js核心库以外,在threejs文件包中examples/jsm目录下,你还可以看到各种不同功能的扩展库。
一般来说,你项目用到那个扩展库,就引入那个,用不到就不需要引入。
javascript
// 引入扩展库OrbitControls.js
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// 引入扩展库GLTFLoader.js
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';javascript
// 扩展库引入——旧版本,比如122, 新版本路径addons替换了examples/jsm
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';