threejs入门一,在网页上看到物体

111 阅读1分钟

一.引入threejs

npm i three
import * as THREE from 'three'

二.初始化3d环境

  1. 创建渲染器,并设置其长宽,然后将其插入到body中
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild( renderer.domElement );

2. 创建场景和相机

// 创建场景
const scene = new THREE.Scene()

// 创建相机
// 张角(我理解为视野角度)
const fov = 70
// 纵横比
const aspect = container.clientWidth / container.clientHeight
// 近裁截面(处于相机与近裁截面的距离的实体不可见)
const near = 0.1
// 远裁截面
const far = 300
// 实例化
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far)

3.创建基础模型.并添加进入场景 创建一个可以在场景中展示的基础模型,首先需要一个几何体(geometry),然后向几何体中添加材质(material),为了方便,这里使用threejs提供的基础网格材质(不受光照影响)

// 创建几何体
const boxGeo = new THREE.BoxGeometry()

// 创建基础材质
const baseMeterial = new THREE.MeshBasicMaterial({
  color: 0x66ccff
})

// 将材质添加到几何体中
const cube = new THREE.Mesh(boxGeo, baseMeterial)

// 添加进场景
scene.add(cube)

4.渲染场景

准备好了所有的东西之后自然要在页面上用canvas渲染出来

function animate() {
  renderer.render( scene, camera );
  requestAnimationFrame(animate)
}

animate()

现在,你应该能在页面上看到一个蓝色正方体了

image.png

5.动起来

我们现在能看到的只有正方体的一个面,想要更好的看到3d效果,我们得让它动起来,最简单的方法就是在动画帧中直接设置模型的旋转角

function animate() {
  cube.rotation.x += 0.005
  cube.rotation.z += 0.005
  renderer.render( scene, camera );
  requestAnimationFrame(animate)
}

animate()