three.js一步一步来--如何画出一个转动的正方体

基础知识--正方体代码如下

<template>
  <div style="1000px; height:800px">
    <h1>正方体</h1>
    <div ref="myBody" />
  </div>
</template>

<script>
import * as THREE from 'three'
import { OBJLoader, MTLLoader } from 'three-obj-mtl-loader'
// import MTLLoader from  'three-mtl-loader';
// import OBJLoader from  'three-obj-loader';
import { CSS2DRenderer, CSS2DObject } from 'three-css2drender'
// import { Geometry, Material, Scene, WebGLBufferRenderer } from 'three';
// const OrbitControls = require('three-orbit-controls')(THREE);
export default {
  data() {
    return {
      scene: new THREE.Scene(), // 场景
      camera: new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        1,
        1000
      ), // 透视相机
      renderer: new THREE.WebGLRenderer(), // 渲染器
      geometry: new THREE.BoxBufferGeometry(1, 1, 1), // 正方体
      material: new THREE.MeshBasicMaterial({ color: 0x00ff00 }), // 设置材料
      cube: new THREE.Mesh(this.geometry, this.material) // 合起來
    }
  },
  mounted() {
    this.init()
    this.render()
  },
  methods: {
    consoleObj() {
      console.log(THREE.REVISION)
      console.log(OBJLoader)
      console.log(MTLLoader)
      console.log(CSS2DRenderer)
      console.log(CSS2DObject)
    },
    init() {
      this.renderer.setClearColor('white') // 渲染器背景色
      this.renderer.setSize(window.innerWidth, window.innerHeight) // 渲染器窗口大小
      this.$refs.myBody.appendChild(this.renderer.domElement) // 放到界面
      this.cube = new THREE.Mesh(this.geometry, this.material) // 不能放在上面,要不然出不來
      this.scene.add(this.cube) // 不能放在上面,要不然出不來
      this.camera.position.z = 5
    },
    render() {
      requestAnimationFrame(this.render) // 游戏循环
      this.cube.rotation.x += 0.1
      this.cube.rotation.y += 0.1
      this.renderer.render(this.scene, this.camera) // 渲染
    }
  }
}
</script>
<style lang="less" scoped></style>

原文地址:https://www.cnblogs.com/sugartang/p/13605618.html