three.js 概述
1-three.js 是什么?
three.js是用JavaScript编写的WebGL第三方库,在我们的课程里就将其简称为three 了。
three 提供了非常多的3D显示和编辑功能。
具体而言,three 是一款运行在浏览器中的 3D 引擎,你可以用three 创建各种三维场景,并对其进行编辑。
在three 的官网上看到许多精彩的演示和文档。
three 官网:threejs.org/
github:github.com/mrdoob/thre…
2-three 的优缺点
优点:
- 对WebGL 进行了深度封装,可以提高常见项目的开发速度。
- 入门简单,精通较难,需图形学基础。
- 具备较好的生态环境,文档详细,持续更新,在国内的使用者很多,就业需求也很大。
缺点:
- 在Node.js 中引用困难。在 Node.js v12 中, three.js 的核心库可使用 require('three') 来作为 CommonJS module 进行导入。然而,大多数在 examples/jsm 中的示例组件并不能够这样。
- 个别功能封装过紧,限制了其灵活性。
3-three 适合做什么
three 适合三维项目的开发和展示,比如VR、AR、三维产品展示、三维家居设计……
three 也可以做游戏开发,只是相较于Babylon,缺少了物理引擎。
牛刀小试-旋转的立方体
接下来我们要搭建一个场景,这个场景里面有一个旋转的立方体。
1.建立一个HTML文件,引入three 。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>牛刀小试p</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="https://unpkg.com/three/build/three.js"></script>
<script>
// Our Javascript will go here.
</script>
</body>
</html>
2.创建一个场景。
const scene = new THREE.Scene();
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 );
我们现在建立了场景、相机和渲染器,对于其中参数的意思,可以去官网查阅文档。
3.创建立方体。
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshNormalMaterial();
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
4.在连续渲染方法里旋转立方体。
animate()
function animate() {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
祝贺你!你现在已经成功完成了你的第一个Three.js应用程序。
虽然它很简单,但现在你已经有了一个入门的起点。