报错
加载glb的代码
load3d() { const loader = new gltfloader() const dracoloader = new dracoloader() dracoloader.setdecoderpath('/draco/') dracoloader.preload() loader.setdracoloader(dracoloader) loader.load('/3d/city.glb', (gltf) => { this.scene.add(gltf.scene) this.renderer.render(this.scene, this.camera) }, (xhr) => { console.log((xhr.loaded / xhr.total) * 100 + '% loaded') }, (error) => { console.error(error) }) }
解决方式
1. glb模型文件请放到public文件下,否则会无法查找到(打包后其他文件都会加上一串编码)
2. 前往node_modules文件下 找到three文件夹, 找到/examples/js/libs/draco/ 将draco整个文件夹复制下来
3. 将复制的draco文件夹复制到public文件夹内
const dracoloader = new dracoloader() dracoloader.setdecoderpath('/draco/')
5. 大功告成
注意:
- 请先保证场景摄像机和光源都是正确的
- 3d/city.glb中的3d是我在public中创建的名为3d的文件夹
完整代码
<template> <section> <section id="container"></section> </section> </template> <script> import * as three from 'three' import { gltfloader } from 'three/examples/jsm/loaders/gltfloader' import { orbitcontrols } from 'three/examples/jsm/controls/orbitcontrols' import { dracoloader } from 'three/examples/jsm/loaders/dracoloader' export default { name: 'index', data() { return { camera: null, scene: null, renderer: null, mesh: null } }, mounted() { this.init() this.animate() }, methods: { init() { const container = document.getelementbyid('container') this.camera = new three.perspectivecamera(90, container.clientwidth / container.clientheight, 0.1, 10000) this.renderer = new three.webglrenderer({ antialias: true }) this.camera.position.set(200, 200, 400) this.scene = new three.scene() this.renderer.setclearcolor(new three.color(0xf7f2f1)) this.renderer.setsize(container.clientwidth, container.clientheight) this.renderer.shadowmap.enabled = true container.appendchild(this.renderer.domelement) this.controls = new orbitcontrols(this.camera, this.renderer.domelement) this.controls.target = new three.vector3(0, 0, 0) this.loadlight() this.load3d() }, load3d() { const loader = new gltfloader() const dracoloader = new dracoloader() dracoloader.setdecoderpath('/draco/') dracoloader.preload() loader.setdracoloader(dracoloader) loader.load('/3d/city.glb', (gltf) => { this.scene.add(gltf.scene) this.renderer.render(this.scene, this.camera) }, (xhr) => { console.log((xhr.loaded / xhr.total) * 100 + '% loaded') }, (error) => { console.error(error) }) }, loadlight() { // 点光源 // const point = new three.pointlight(0xffffff) // point.position.set(4000, 4000, 4000) // 点光源位置 // this.scene.add(point) // 点光源添加到场景中 // 环境光 const ambient = new three.ambientlight(0xffffff) this.scene.add(ambient) }, animate() { requestanimationframe(this.animate) this.renderer.render(this.scene, this.camera) } } } </script> <style scoped> #container { width: 100%; height: calc(100vh - 84px); } </style>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论