Abel'Blog

我干了什么?究竟拿了时间换了什么?

0%

ThreeJs

简介

开一篇文章专门记录学习three.js相关的知识。

开始

第一个实例

直接通过一个例子来看如何展示一个旋转的box。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<!-- 引入three.js文件,这个文件可以从他们的官网直接下载到。 -->
<script src="js/three.js"></script>
<script>
// 创建一个场景对象
const scene = new THREE.Scene();
// 创建透视方式的摄像机,也有正交方式的摄像机可选。
// 摄像机的参数: fov 75°视角 aspect 宽高比例 near 视野最近 far 视野最远
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() {
requestAnimationFrame( animate );

// 让方块x,y的方向上旋转0.01°
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;

renderer.render( scene, camera );
};
// 调用动画
animate();
</script>
</body>
</html>

安装

可以通过npm来安装。可以通过CDN来安装。

如何本地运行

可以直接通过运行一个服务器来跑这个html页面。本章提供的的可选的服务器:

five-server

gui-web-server

node-http-server。

python -m SimpleHTTPServer

php -S localhost:8000

画线

1
2
//create a blue LineBasicMaterial
const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );

加载3d模型

能支持很多的3d模型文件格式。

库与插件

里面包含了物理插件,粒子系统,AI系统等等。

引用