最近接到一个新的需求,再登陆页添加这样的背景效果(如上图),很显然这是three.js的,所以需要再之前的老项目中引入three.js,但是vue-cli2和vue-cli3引入后有些情况不同,下面开始吧!
安装依赖
npm i three -D
npm i three-orbit-controls -D // 控制移动的效果(放大,360度旋转,平移)
然后直接再页面中上代码,如下
<template>
<div>
<div id="container"></div>
</div>
</template>
<script>
import * as THREE from "three"; // 引入three
const OrbitControls = require("three-orbit-controls")(THREE);
export default {
name: "index",
data() {
return {
camera: null,
scene: null,
renderer: null,
mesh: null,
};
},
methods: {
init() {
let container = document.getElementById("container");
// 创建一个相机 参数:fov、aspect、near、far
this.camera = new THREE.PerspectiveCamera(30, 1, 0.01, 1000);
// 相机离屏幕的距离
this.camera.position.z = 1;
// 创建场景
this.scene = new THREE.Scene();
// 创建一个立方体 参数 width、height、depth
let geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
// 立方体的材质 参数为obj
let material = new THREE.MeshNormalMaterial({ color: 0x00ff00 });
// 将立方体和材质包添加到网格
this.mesh = new THREE.Mesh(geometry, material);
// 将网格添加到场景中
this.scene.add(this.mesh);
// 渲染器 参数为obj antialias:true 开启抗锯齿(默认为false)
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setClearColor(0xb9d3ff, 1);
// 设置渲染大小
this.renderer.setSize(500, 500);
this.renderer.render(this.scene, this.camera);
container.appendChild(this.renderer.domElement);
new OrbitControls(this.camera,this.renderer.domElement)
},
animate() {
requestAnimationFrame(this.animate);
this.mesh.rotation.x += 0.01;
this.mesh.rotation.y += 0.01;
this.renderer.render(this.scene, this.camera);
},
},
mounted() {
this.init();
this.animate();
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#container {
position: absolute;
width: 100%;
height: 100%;
}
</style>
最后展示的效果如下,便说明成功了
下面就随意自己秀了!!!
报错问题
在vue-cli2中,会出现以下的报错
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
(node:5224) [DEP0111] DeprecationWarning: Access to process.binding('http_parser') is deprecated.(Use `node --trace-deprecation ...` to show where the warning was created)
13% building modules 26/31 modules 5 active ...x=0!E:\test\thcode\t3demo\src\App.vue{ parser: "babylon" } is deprecated; we now treat it as { parser: "babel" }.
94% asset optimization
ERROR Failed to compile with 1 errors
error in ./node_modules/_three@0.132.2@three/build/three.module.js
Module parse failed: Unexpected token (2516:25)
You may need an appropriate loader to handle this file type.
|
| this.texture = source.texture.clone();
| this.texture.image = { ...this.texture.image }; // See #20328.
|
| this.depthBuffer = source.depthBuffer;
@ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src
大概意思就是: 您可能需要一个适当的加载器来处理这种文件类型。就是没有对应的loader来处理的问题;
解决方法
安装低版本的three —— 0.128.0 (我现在的版本是0.135.0)
//卸载three
npm uninstall three
// 安装 0.128.0版本的
npm install three@0.128.0
重启,运行,成功~~