一、准备工作
npm安装特定版本three.js(注意使用哪个版本,查文档就查对应版本)
// 比如安装148版本
npm install three@0.148.0 --save
npm安装后,如何引入three.js
执行import * as THREE from 'three';,ES6语法引入three.js核心。
// 引入three.js
import * as THREE from 'three';
扩展库
除了three.js核心库以外,在threejs文件包中examples/jsm目录下,你还可以看到各种不同功能的扩展库。
一般来说,你项目用到那个扩展库,就引入那个,用不到就不需要引入。
// 引入扩展库OrbitControls.js
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// 引入扩展库GLTFLoader.js
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
二、three.js三大要素
要渲染物体到网页中,我们需要3个组件:场景(scene)、相机(camera)和渲染器(renderer)。有了这三样东西,才能将物体渲染到网页中去。
1、 场景(scene)
场景对象
// 创建3D场景对象Scene
const scene = new THREE.Scene();
几何体
//创建一个长方体几何对象Geometry
const geometry = new THREE.BoxGeometry(100, 100, 100);
材质对象
//创建一个材质对象Material
const material = new THREE.MeshBasicMaterial({
color: 0xff0000,//0xff0000设置材质颜色为红色
});
网格模型对象
// 两个参数分别为几何体geometry、材质material
const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
三维空间位置坐标
//设置网格模型在三维空间中的位置坐标,默认是坐标原点
mesh.position.set(0,10,0);
添加到场景
scene.add(mesh);
2、 相机(camera)
实例化相机对象
// 实例化一个透视投影相机对象
const camera = new THREE.PerspectiveCamera();
相机三维坐标系
//相机在Three.js三维坐标系中的位置
// 根据需要设置相机位置具体值
camera.position.set(200, 200, 200);
相机观察目标
//相机观察目标指向Threejs 3D空间中某个位置
camera.lookAt(0, 0, 0); //坐标原点
//或
camera.lookAt(0, 10, 0); //y轴上位置10
//或
camera.lookAt(mesh.position);//指向mesh对应的位置
画布尺寸
// width和height用来设置Three.js输出的Canvas画布尺寸(像素px)
const width = 800; //宽度
const height = 500; //高度
// 30:视场角度, width / height:Canvas画布宽高比, 1:近裁截面, 3000:远裁截面
const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
3、 渲染器(renderer)
创建渲染器对象
// 创建渲染器对象
const renderer = new THREE.WebGLRenderer();
设置渲染区域
renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
渲染器渲染方法.render()
renderer.render(scene, camera); //执行渲染操作
渲染器Canvas画布属性.domElement
document.body.appendChild(renderer.domElement);
Canvas画布插入到任意HTML元素中
<div id="box" style="margin-top: 200px;margin-left: 100px;"></div>
document.getElementById('box').appendChild(renderer.domElement);