Threejs

Threejs

官网:https://threejs.org/

github仓库:https://github.com/mrdoob/three.js

环境

本地

下载依赖包

  • 核心文件:在官方仓库的/build下的three.module.js
  • 插件:在/examples/jsm

本地运行

​ vscode安装live-server插件,右键想要运行的html文件,点击Open with Live Server

引入threejs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 在examples下的代码中可以找到官方写的导入代码
// three.module.js是运行基本的 three.js 应用程序所需的唯一文件
// 路径根据实际情况修改
<script type="importmap">
{
"imports": {
"three": "./build/three.module.js"
}
}
</script>

<script type="module">
import * as THREE from 'three';
// 浏览器控制台测试,是否引入成功
console.log(THREE.Scene);
</script>
  • type="importmap"用于模块路径映射,减少打包工具的依赖。
  • type="module"是现代前端开发的标准方式,支持 import/export

基本概念

场景Scene:虚拟的3D场景

几何体Geometry:文档搜索geometry,可以找到不同几何体的创建和实例

材质Material:定义物体的外观效果

网格模型Mesh:将几何体和材质结合,形成可以在3D场景中渲染的物体

相机Camera:想把三维场景Scene渲染到web网页上,还需要定义一个虚拟相机

1
2
// 常用的透视投影相机的构造函数
PerspectiveCamera( fov : Number, aspect : Number, near : Number, far : Number )

每个参数的意思

渲染器Renderer:将 3D 场景 和 相机 渲染到 HTML <canvas>元素上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 创建场景
const scene = new THREE.Scene();
// 创建几何体
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 );

const width = 800;
const height = 500;
// 创建透视投影相机
// 30:视场角度, width / height:Canvas画布宽高比, 1:近裁截面, 3000:远裁截面
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
camera.lookAt(cube.position);
scene.add( camera );

// 创建WebGL渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
renderer.render(scene, camera);
document.getElementById('webgl').appendChild(renderer.domElement);

Threejs
http://xwww12.github.io/2025/07/14/前端/JS库/threejs/
作者
xw
发布于
2025年7月14日
许可协议