一直想搞一下Threejs,并希望能够用到Vue-cli中配合着vue开发,今天结合网上的知识和Threejs的书籍写一个如下demo,作为第一次编写入门,也希望对大家有所帮助!

源码:​​my3dtest: 我的前端测试仓库!使用Vue和Threejs来娱乐3D​

1.首先创建vue项目


命令: vue init webpack my3dtest    //my3dtest是项目名,可修改


2.引入three包


npm install --save three 


3.demo 效果

 Vue-cli + Threejs 第一个小测试Demo_vue-cli

4.代码实现:My3D001.vue

<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 {
name: "My3D001",
data(){
return{
camera:null,
scene:null,
renderer:null,
mesh:null,
controls:null
}
},
mounted() {
this.init();
this.animate()
},
methods:{
init(){
//创建场景对象Scene
this.scene = new THREE.Scene();
//创建网格模型 并设置其参数和材质
let geometry = new THREE.BoxGeometry(0.2,0.2,0.2);
let material = new THREE.MeshNormalMaterial({
color:0x0000ff
});
this.mesh = new THREE.Mesh(geometry,material);
//将创建的网格添加到场景中
this.scene.add(this.mesh);

//创建点光源
var point = new THREE.PointLight(0xffffff);
point.position.set(400,200,300);
this.scene.add(point);
//创建环境光
var anbient = new THREE.AmbientLight(0x444444);
this.scene.add(anbient);

//相机设置
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.WebGL1Renderer({antialias:true});
this.renderer.setSize(container.clientWidth,container.clientHeight);//设置渲染区域尺寸
this.renderer.setClearColor(0xb9d3ff,1);//设置背景颜色
container.appendChild(this.renderer.domElement);//将渲染器绑定到div标签

//创建控件对象
this.controls = new OrbitControls(this.camera,this.renderer.domElement);

},
//动画
animate(){
requestAnimationFrame(this.animate);
this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.02;
this.renderer.render(this.scene,this.camera);
}
}


}
</script>

<style scoped>
#container{
position: absolute;
width: 100%;
height: 100%;
}
</style>

在路由文件里修改路由:

import Vue from 'vue'
import Router from 'vue-router'
import My3D001 from '../views/My3D001'

Vue.use(Router)

export default new Router({
routes: [
{
path: '/',
name: 'My3D001',
component: My3D001,
}
]
})