天天看點

(二) 記錄H5做AR的過程,關于Three.js在Vue中的簡單應用

首先需要使用Three.js必須先引入子產品

  • 你可以選擇script的方式快速引用

    <script src="js/three.js"></script>

  • 或者通過子產品來引入,雖然通過script标簽來引入three.js是一個能夠快速起步、快速運作的方式,但這種方式對于一些具有較長生命周期的項目來說是有一些缺點。比如:
    • 你必須手動獲得并在你的項目源代碼中包含這個庫的一個拷貝
    • 更新庫的版本是一個手動操作的過程
    • 在檢查新版本的庫時,你的版本差異對比将會被許多行的建構檔案給弄亂。

通過npm來安裝

Three.js目前已經作為一個npm子產品來進行了釋出,隻需運作"npm install three"就可以使你的項目包含three.js庫。

導入這個子產品

這次示範使用ES6的方式(import語句)

import * as THREE from 'three';

const scene = new THREE.Scene();
...

           

或者,如果你希望隻導入three.js庫中的特定部分,例如Scene:

import { Scene } from 'three';

const scene = new Scene();
...
           

如何在vue中使用

以下是一個立方體的簡單的例子 後續會加上

codepen

的示例

<template>
    <div>
      <div id="container"></div>
    </div>
</template>
 
<script>
import * as Three from 'three'
 
export default {
  name: 'Demo',
  data() {
    return {
      camera: null,
      scene: null,
      renderer: null,
      mesh: null
    }
  },
  methods: {
    init: function() {
        let container = document.getElementById('container');
        //添加相機
        this.camera = new Three.PerspectiveCamera(70, container.clientWidth/container.clientHeight, 0.01, 10);
        this.camera.position.z = 1;
        //添加場景
        this.scene = new Three.Scene();
        //添加立方體
        let geometry = new Three.BoxGeometry(0.2, 0.2, 0.2);
        //使用材質
        let material = new Three.MeshNormalMaterial();
        //添加網格
        this.mesh = new Three.Mesh(geometry, material);
        //加入場景
        this.scene.add(this.mesh);
        //加入渲染器 antialias為true是打開抗鋸齒 優化顯示一些機器好的裝置
        this.renderer = new Three.WebGLRenderer({antialias: true});
        this.renderer.setSize(container.clientWidth, container.clientHeight);
        //添加到子節點
        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 {
    width: 100vw;
    height: 100vh;
  }
</style>
           

歡迎來我的部落格檢視更多 https://blog.xollipop.top/