在使用THREE的过程中,发现很多例子都是用了ES6的语法,在调试时,需要将其进行编译。笔者尝试了用parcel进行搭建个人应用环境,也可以,但是相对而言,还是VUE更加方便。
该处以VUE2 为例,介绍THREE(案例一)在VUE中的使用。
首先创建VUE项目
vue create <project name>
接着安装Three
npm install three
在使用three需要引入对应的文件
本文以创建的默认文件【HelloWorld.vue】为例,直接对该文件进行修改。
<script>
//核心库
import * as THREE from "three"
//控制器,可以让用户在场景中自由移动和旋转相机,以便更好地查看场景
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls"
</script>
依旧和【文章一】中的步骤一样,{场景、相机、渲染器}三者的创建。
首先在data中建立对应的字段
data(){
return {
scene:null,
camera:null,
renderer:null,
//宽高声明
width:0,
height:0
}
}
同样,我们需要设置div。
<template>
<div class="webgl-container">
<div id="webglDom" ref="webglDom"></div>
</div>
</template>
接着,在使用时,我们需要获取当前屏幕的可视大小
const container = this.$refs.webglDom;
this.width = container.offsetWidth;
this.height = container.offsetHeight;
这样初始条件就设置好了,接下来就可以生成对应的条件了
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(45, this.width / this.height, 0.01, 10000);
this.camera.position.z = 5;
this.add(this.camera);
this.camera.lookAt(this.scene.position);
// AxesHelper
let axisHelper = new THREE.AxesHelper(100, 100);
this.add(axisHelper);
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({
color: "skyblue"
});
const mesh = new THREE.Mesh(geometry, material);
this.add(mesh);
// 渲染器
this.renderer = new THREE.WebGLRenderer({
antialias: true
})
this.renderer.setSize(this.width, this.height);
document.getElementById("webglDom").appendChild(this.renderer.domElement);
// OrbitControls
new OrbitControls(this.camera, this.renderer.domElement);
this.render();
//部分需求函数,存放在methods中
add (obj) {
this.scene.add(obj);
},
render() {
this.renderer.render(this.scene, this.camera);
requestAnimationFrame(this.render);
}
样式设置
#webglDom{
width: 100%;
height: 800px;
overflow: hidden;
}
.webgl-container{
width: 100%;
height: 800px;
overflow: hidden;
}
通过
npm run serve
即可运行。
![](https://i-blog.csdnimg.cn/blog_migrate/c616b6d1b6258d6096b416ac4bd84900.png)