说明:事先安装three.js,npm install three --save 并将其绑定在vue上;在main.js中这样绑定;
import * as Three from 'three'
Vue.prototype.$THREE = Three
代码如下:
<template>
<div :style="{'maxHeight':maxHeight + 'px'}">
<div id="demo"></div>
</div>
</template>
<script>
export default {
data() {
return {
scene: null, // 场景对象
camera: null, // 相机对象
mesh: null, // 网格对象
maxHeight: 500, //
maxWidth: '100%' //
};
},
mounted() {
this.getTableHeight();
this.initScene();
this.initCamera();
this.initRenderer();
this.initGemotry();
this.renderMethod();
},
methods: {
getTableHeight() {
var height = document.body.clientHeight - 230;
this.maxHeight = height;
this.maxWidth = window.innerWidth - 280;
},
// 初始化场景方法
initScene() {
this.scene = new this.$THREE.Scene();
},
// 初始化相机方法
initCamera() {
// 创建相机对象
this.camera = new this.$THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
this.camera.position.z = 10;
},
// 初始化渲染器的方法
initRenderer() {
this.renderer = new this.$THREE.WebGLRenderer();
this.renderer.setSize(this.maxWidth, this.maxHeight);
document.getElementById("demo").appendChild(this.renderer.domElement);
},
// 初始化立方体对象
initGemotry() {
var gemotry = new this.$THREE.BoxGeometry(4, 3, 3, 3, 3, 3); // 创建几何体
var material = new this.$THREE.MeshBasicMaterial({ color: 0x00ff00 }); // 创建材质
this.mesh = new this.$THREE.Mesh(gemotry, material); // 创建网格
this.scene.add(this.mesh); // 场景中添加网格
},
// 开始渲染
renderMethod() {
requestAnimationFrame(this.renderMethod);
this.renderer.render(this.scene, this.camera);
this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.01;
}
}
};
</script>
<style lang="scss" scoped>
</style>