threejs学习笔记-加载模型

96 阅读1分钟
```<template>

  <div class="content">
    <canvas id="c"></canvas>
  </div>
</template>

<script>
import * as THREE from "three"
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader"
import {DRACOLoader} from "three/examples/jsm/loaders/DRACOLoader"
import * as Three from "three"

export default {
  name: "module",
  data() {
    return {
      renderer: null,
      scene: null,
      camera: null,
      controls: null
    }
  },
  mounted() {
    this.init()
    this.animate()
  },
  methods: {
    init() {
      // 渲染器
      const canvas = document.querySelector('#c')
      this.renderer = new THREE.WebGLRenderer({antialias: true, canvas})
      this.renderer.setClearColor(new THREE.Color(0x000000))
      this.renderer.setSize(canvas.clientWidth, canvas.clientHeight)
      this.renderer.shadowMap.enabled = true
      // 相机
      this.camera = new THREE.PerspectiveCamera(5, canvas.clientWidth / canvas.clientHeight, 0.1, 1000)
      this.camera.position.set(0, 150, 50)
      // 场景
      this.scene = new THREE.Scene()

      // 轨道控制
      this.controls = new OrbitControls(this.camera, this.renderer.domElement)
      this.controls.target = new Three.Vector3(0, -10, 0)

      this.load3D()
    },
    load3D() {
      const loader = new GLTFLoader()
      const dracoLoader = new DRACOLoader()
      dracoLoader.setDecoderPath('/draco/')
      dracoLoader.preload()
      loader.setDRACOLoader(dracoLoader)

      loader.load('/deir_el-sultan_jerusalem.glb', (gltf) => {
        this.scene.add(gltf.scene)
        this.renderer.render(this.scene, this.camera)
      }, (xhr) => {
      }, (error) => {
        console.error(error)
      })
    },
    animate() {
      requestAnimationFrame(this.animate)
      this.renderer.render(this.scene, this.camera)
    }
  }
}
</script>

<style scoped lang="less">
.content {
  width: 100%;
  height: 100vh;
  overflow: hidden;

  #c {
    width: 100%;
    height: 100%;
  }

}
</style>
```

资源地址:

gitee.com/chenshuai56…

效果图