vue和three(一)

86 阅读1分钟

1、创建工程

vue create vue-three

2、安装包

npm install three

3、代码页

<template>
  <div id="hello">

  </div>
</template>

<script>
import * as THREE from "three"
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      scene: null,//场景
      camera: null,//摄像机
      renderer: null,//渲染对象
      controls:null, //控制器
    }
  },
  mounted() {
    this.initScene() //初始化场景
    this.addModel() //模型
    this.initLinght() //初始化光源
    this.initCamera() //初始化摄像机
    this.initRenderer() //初始化渲染对象

    this.initControls() //控制

    this.animation() //执行渲染

    window.onresize = this.onWindowResize //窗口变化
  },
  methods: {
    initScene() {
      this.scene = new THREE.Scene()
    },
    addModel() {
      const geometry = new THREE.BoxGeometry(20, 20, 20);
      const material = new THREE.MeshNormalMaterial();

      const mesh = new THREE.Mesh(geometry, material);
      this.scene.add(mesh);

    },
    initLinght() {
      const point = new THREE.PointLight(0xffffff)  //创建点光源
      point.position.set(600, 900, 600);
      this.scene.add(point) //点光源添加到场景

      // //环境光
      // const ambient = new THREE.AmbientLight(0xffffff)
      // this.scene.add(ambient)
    },
    initCamera() {
      this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000)
      this.camera.position.set(60, 100, 60)
      this.camera.lookAt(this.scene.position)
    },
    initRenderer() {
      const container = document.getElementById("hello")
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.renderer.setSize(container.clientWidth, container.clientHeight)  //设置渲染尺寸
      container.appendChild(this.renderer.domElement)  //渲染到指定id元素上
    },
    initControls(){
      this.controls=new OrbitControls( this.camera, this.renderer.domElement );
    },
    animation() {
      this.renderer.render(this.scene, this.camera)
      requestAnimationFrame(this.animation)
    },
    onWindowResize() {
      this.camera.aspect = window.innerWidth / window.innerHeight
      // 渲染器执行render方法的时候会读取相机对象的投影矩阵属性projectionMatrix
      // 但是不会每渲染一帧,就通过相机的属性计算投影矩阵(节约计算资源)
      // 如果相机的一些属性发生了变化,需要执行updateProjectionMatrix ()方法更新相机的投影矩阵
      this.camera.updateProjectionMatrix
      const container = document.getElementById("hello")
      this.renderer.setSize(container.clientWidth, container.clientHeight)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#hello {
  width: 100%;
  height: 100vh;
  position: absolute;
}
</style>