three.js 初体验 (一)基础图形

2020-04-18  本文已影响0人  locky丶

随着我们的上网设备的硬件条件和网速的不断提升,浏览器对于3d画面的渲染速度越来越快,3d正在被更多的重视和应用。
所以我也赶着这波趋势,研究下three.js -- 用javaScript编写的3d库。

PS:由于我们项目多用vue,以下示例代码都是在vue组件内编写。

首先是在项目内安装three.js包

npm install three --save-dev
// or
yarn add three

创建一个vue组件,并写入如下代码

<template>
    <div>
      <div id="container"></div>
    </div>
</template>

<script>
import * as Three from 'three'

export default {
  name: 'ThreeTest',
  data () {
    return {
      camera: null,
      scene: null,
      renderer: null,
      mesh: null
    }
  },
  methods: {
    init: function () {
      const container = document.getElementById('container')
      // 创建场景
      this.scene = new Three.Scene()

      // 创建相机
      this.camera = new Three.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.0001, 10)
      this.camera.position.z = 1
      
      // 定义形状
      const geometry = new Three.BoxGeometry(0.4, 0.4, 0.4)
      // 定义材质
      const material = new Three.MeshNormalMaterial()

      // 创建网格系统
      this.mesh = new Three.Mesh(geometry, material)

      // 网格系统加入场景
      this.scene.add(this.mesh)

      // 创建渲染器
      this.renderer = new Three.WebGLRenderer({ antialias: true })
      // 设置渲染器尺寸
      this.renderer.setSize(container.clientWidth, container.clientHeight)
      // 将场景和相机放入到渲染器中
      this.renderer.render(this.scene, this.camera)
      // 放入到页面中
      container.appendChild(this.renderer.domElement)
    },
    animate: function () {
      // 逐帧动画
      requestAnimationFrame(this.animate)
      // 设置旋转速度
      this.mesh.rotation.x += 0.01
      this.mesh.rotation.y += 0.02
      // 每动一次,渲染一下,让画面动起来
      this.renderer.render(this.scene, this.camera)
    }
  },
  mounted () {
    this.init()
    this.animate()
  }
}
</script>
<style scoped>
  #container {
    height: 400px;
  }
</style>

现在运行项目,我们就能看到一个3d立方体在画面中。
大体的理解下这段代码:
// init 函数中:

  1. 创建一个id为container的dom。
  2. 创建一个场景 scene。
  3. 创建一台相机 camera,相机的焦段为75,宽高比为 “屏幕的宽度/屏幕的高度”,最远点位设为0.0001,最近点位设为10。
  4. 创建一个物体 geometry,这是个立方体,长宽高都是0.2。
  5. 生成一个材质 material,默认的,没给参数。
  6. 创建一个网格mesh,利用网格把材质绑定到物体上。
  7. 将mesh 加入到场景 scene 中。
    此时画面中还是一片空白,我们还差最后一步,渲染
  8. 创建一个渲染器renderer,设置渲染器尺寸。
  9. 将场景和相机加入到渲染器中。
  10. 将渲染器中的所有元素,添加到我们第一步时创建的container中。
    到这步我们就创建完了,下面我们要让物体运动起来
    // animate函数中
  11. 调用requestAnimationFrame(),有点类似setInterval, 它是window下的方法,可以直接调用。
    看下MDN上给它的解释: window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。
  12. 给mesh的x轴设置旋转速度值, 给mesh的y轴设置旋转速度值。
  13. 每更新一次mesh的位置,就要重新执行一次 this.renderer.render(this.scene, this.camera) , 这就跟我们看电影一样,每一帧画面都要渲染一次,为什么电脑制作特效这么贵,大部分都花在渲染画面上了。
  14. mounted 执行下init 和 animate 这两个方法,您的第一个三维动画就告成了。
上一篇下一篇

猜你喜欢

热点阅读