创建vue项目(略)
执行如下命令:安装threejs相关模块
npm install three
npm install three-css2drender
npm install three-obj-mtl-loader
npm install three-orbit-controls
package.json 如下
{
"name": "vue-lk-test",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "npm run serve",
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.21.0",
"compression-webpack-plugin": "^6.0.3",
"core-js": "^3.6.5",
"nprogress": "^0.2.0",
"postcss-px2rem": "^0.3.0",
"three": "^0.121.1",
"three-css2drender": "^1.0.0",
"three-obj-mtl-loader": "^1.0.3",
"three-orbit-controls": "^82.1.0",
"uglifyjs-webpack-plugin": "^2.2.0",
"vue": "^2.6.11",
"vue-router": "^3.4.7",
"vuex": "^3.5.1",
"webpack-bundle-analyzer": "^3.9.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
创建test.vue测试文件
import * as Three from 'three'
说明:three.js显示任何内容,我们需要三件事:场景,相机和渲染器,以便我们可以使用相机渲染场景。
在methods中创建init方法
init() {
// 获取3D容器元素
let container = document.getElementById('container');
// 构建场景
let scene = new Three.Scene();
}
如下图:
// 构建相机
// 参数说明 视野:75度,长宽比,近平面裁剪:0.1,远平面裁剪:1000
let camera = new Three.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000 );
// 构建渲染器
let renderer = new Three.WebGLRenderer();
// 设置宽高,
renderer.setSize(container.clientWidth/2,container.clientHeight/2);
数据集中包含盒子模型和颜料着色器
// 构建多维数据集
// 构建集合图形,包含所有点和面
let box = new Three.BoxGeometry();
// 构建颜料着色器
let material = new Three.MeshBasicMaterial({color: 0x00ff00});
// 构建数据集
let cube = new Three.Mesh(box,material);
// 数据集添加到场景
scene.add(cube);
// 设置相机的远近
camera.position.z=5;
// data属性赋值
this.scene = scene;
this.camera = camera;
this.renderer = renderer;
this.cube = cube;
// 渲染器添加到页面容器
container.appendChild( renderer.domElement );
在methods中添加如下方法
animate() {
// 调用自己,创建一个循环
// 不使用setInterval,好处是,离开当前路由,循环将终止,节省资源
requestAnimationFrame(this.animate);
// 改变场景
this.change();
// 重新渲染
this.renderer.render( this.scene, this.camera );
},
change(){
// 添加场景变化
}
将init方法和animate方法添加到mounted中:
mounted () {
this.init();
this.animate();
}
此时,我们得到一个图形,但没有什么动作
change(){
// 添加场景变化 -- 数据集变化
this.cube.rotation.x += 0.01;
this.cube.rotation.y += 0.01;
}
此时,我们将看到一个循环旋转变化的3D图形。