??本篇文章主要针对小白在使用threejs中所遇到的问题,因为我就是小白,接下来会和大家一起慢慢成长。
??推荐几个学习的地址:
??TRHEE.js中文网??
??TRHEE.js 哔哩哔哩学习视频??
??TRHEE.js 官方地址??
??TRHEE.js GitHub地址??
??在.html 文件中主要是通过引用threejs(点击下载three.js),若是想使用 OrbitControls,GLTFLoader这些,可以单独到 threejs GitHub上进行下载并引入
也可以直接引用下面这个地址
1 | <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script> |
??下面主要介绍 vue 在引入 threejs 中遇到的问题:
1.组件怎么引用,这里的 OrbitControls 这些不能直接引入,需要进行一些操作后才能引入 点击查看如何引入。
因为我用的是 vue-cli3.0,所以需要创建一个 vue.config.js,引入后就不会报错了 。<点击查看 vue.config.js的相关配置>
vue.config.js 配置
1 | const ThreeExamples = require('import-three-examples') |
1 2 3 4 5 | // 第三方插件配置 pluginOptions: { // ... ...ThreeExamples } |
首先 npm install --s three
组件内引用
1 | import * as THREE from "three"; |
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | <template> <div> <div id="container"></div> </div> </template> <script> import * as THREE from "three"; import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js'; export default { data() { return { camera: null, scene: null, renderer: null, mesh: null, controls:null }; }, mounted() { this.init(); this.animate(); }, methods: { //初始化 init: function() { // 创建场景对象Scene this.scene = new THREE.Scene(); //网格模型添加到场景中 let geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2); let material = new THREE.MeshNormalMaterial({ color: "white" }); this.mesh = new THREE.Mesh(geometry, material); this.scene.add(this.mesh); /** * 相机设置 */ let container = document.getElementById("container"); this.camera = new THREE.PerspectiveCamera( 70, container.clientWidth / container.clientHeight, 0.01, 10 ); this.camera.position.z = 1; /** * 创建渲染器对象 */ this.renderer = new THREE.WebGLRenderer({ antialias: true }); this.renderer.setSize(container.clientWidth, container.clientHeight); container.appendChild(this.renderer.domElement); //创建控件对象 this.controls = new OrbitControls(this.camera, 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); } } }; </script> <style> #container { position: absolute; width: 100%; height: 100%; } </style> |