three.js(一):认识three.js并创建第一个3D应用

three.js 概述

1-three.js 是什么?

    three.js是用JavaScript编写的WebGL第三方库; three.js 提供了非常多的3D显示和编辑功能; 具体而言,three.js 是一款运行在浏览器中的 3D 引擎,可以用three.js 创建各种三维场景,并对其进行编辑; 在three.js 的官网上看到许多精彩的演示和文档 three.js 官网: github:

2-three 的优缺点

优点:

    对WebGL 进行了深度封装,可以提高常见项目的开发速度。 入门简单,精通较难,需图形学基础。 具备较好的生态环境,文档详细,持续更新,在国内的使用者很多,就业需求也很大。

缺点:

    在Node.js 中引用困难。在 Node.js v12 中, three.js 的核心库可使用 require(‘three’) 来作为 CommonJS module 进行导入。然而,大多数在 examples/jsm 中的示例组件并不能够这样。 个别功能封装过紧,限制了其灵活性。

3-three 适合做什么

    three.js 适合三维项目的开发和展示,比如VR、AR、三维产品展示、三维家居设计…… three.js 也可以做游戏开发,只是相较于Babylon,缺少了物理引擎。

创建第一个3D应用-旋转的立方体

1.建立一个HTML文件,引入three

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>立方体</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应用程序
经验分享 程序员 微信小程序 职场和发展