three.js+vue实现一个正方体demo添加点击事件

2,712 阅读1分钟

首先先要引入three.js到vue项目中,然后引入import * as Three from 'three' 文末放效果图

	<div id="container" @click='onMouseClick($event)'>
	</div>
</template>

<script>
	import * as Three from 'three' // 引入three
	export default {
		data() {
			return {
				camera: null,
				scene: null,
				renderer: null,
				mesh: null,
				raycaster: null,
				mouse:null,
				tag:0,
			}
		},
		methods: {
			onMouseClick(e) {
				//X轴,Y轴,Z轴旋转的弧度
				if(this.tag == 0){
					this.mesh.scale.set(3,3,3)
					this.tag = 1
				}else if(this.tag == 1){
					this.mesh.scale.set(1,1,1)
					this.tag = 0
				}

			},
			init: function() {
				//获取DOM容器
				let container = document.getElementById('container');
				//设置相机的角度  宽高比  近端面  远端面
				this.camera = new Three.PerspectiveCamera(45, container.clientWidth / container.clientHeight, 0.1, 1000);
				//设置相机在三维坐标的位置
				this.camera.position.set(0, 0, 2)
				//this.camera.position.z = 1;
				//设置场景
				this.scene = new Three.Scene();
				//添加正方体  参数分别是长  宽  高
				let geometry = new Three.BoxGeometry(0.3, 0.3, 0.3);
				//添加材质
				let material = new Three.MeshNormalMaterial();
				//将正方体以及材质放入网格中
				this.mesh = new Three.Mesh(geometry, material);
				//在场景中添加网格
				this.scene.add(this.mesh);
				//开启反锯齿
				this.renderer = new Three.WebGLRenderer({
					antialias: true
				});
				//指定渲染器的高宽(和画布框的大小一致)
				this.renderer.setSize(container.clientWidth, container.clientHeight);
				//将指定的渲染器加入到Dom容器中
				container.appendChild(this.renderer.domElement);

			},
			//动画效果函数
			animate: function() {
				//回调执行这个函数
				requestAnimationFrame(this.animate);
				//X轴,Y轴,Z轴旋转的弧度
				this.mesh.rotation.x += 0.008;
				this.mesh.rotation.y += 0.008;
				// this.mesh.rotation.z += 0.008;
				//渲染相机以及场景
				this.renderer.render(this.scene, this.camera);
			}
		},

		mounted() {
			//调用初始化和animate的函数效果
			this.init();
			this.animate()
		}

	}
</script>
<style scoped>
	#container {
		height: 900px;
	}
</style>`

1635906871(1).jpg