作者: 还是大剑师兰特 ,曾为美国某知名大学计算机专业研究生,现为国内GIS领域高级前端工程师,CSDN知名博主,深耕openlayers、leaflet、mapbox、cesium,canvas,echarts等技术开发,欢迎加微信(gis-dajianshi),一起交流。
004
个示例
文章目录
一、示例效果图
二、示例简介
本threeJS示例通过不同的Geometry创建两个几何体,一个box,另一个球体,通过监听键盘的空格键,来切换显示不同的几何体。
三、配置说明
1)查看基础设置:https://dajianshi.blog.csdn.net/article/details/141936765
2)将示例源代码,粘贴到src/views/Home.vue中,npm run serve 运行即可。
四、示例源代码(共105行)
/*
* @Author: 大剑师兰特(xiaozhuanlan),还是大剑师兰特(CSDN)
* @此源代码版权归大剑师兰特所有,可供学习或商业项目中借鉴,未经授权,不得重复地发表到博客、论坛,问答,git等公共空间或网站中。
* @Email: 2909222303@qq.com
* @First published in xiaozhuanlan
* @Second published in CSDN
* @First published time: 2024-09-24
*/
<template>
<div class="container">
<h3>ThreeJS示例(004): 监听键盘空格键,切换两个不同的几何体</h3>
<p>大剑师兰特, 还是大剑师兰特</p>
<div id="vue-three"></div>
</div>
</template>
<script>
import * as THREE from "three";
export default {
data() {
return {
}
},
methods: {
initThree() {
// 创建场景
var scene = new THREE.Scene();
// 创建相机
var camera = new THREE.PerspectiveCamera(75, 96 / 53, 0.1, 1000);
camera.position.z = 5;
// 创建渲染器
var renderer = new THREE.WebGLRenderer();
renderer.setSize(960, 530);
let dom = document.getElementById('vue-three');
dom.appendChild(renderer.domElement);
// 创建两个几何体
const boxGeometry = new THREE.BoxGeometry(1.2, 1.2, 1.2);
const sphereGeometry = new THREE.SphereGeometry(0.5, 32, 32);
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
// 默认显示一个几何体
let currentMesh = new THREE.Mesh(boxGeometry, material);
scene.add(currentMesh);
// 创建另一个几何体备用
const boxMesh = currentMesh;
const sphereMesh = new THREE.Mesh(sphereGeometry, material);
// 切换几何体
function switchGeometry() {
if (currentMesh === boxMesh) {
// 如果当前是box,则切换成sphere
scene.remove(currentMesh);
currentMesh = sphereMesh;
scene.add(currentMesh);
} else {
// 如果当前是sphere,则切换成box
scene.remove(currentMesh);
currentMesh = boxMesh;
scene.add(currentMesh);
}
}
// 监听键盘事件
document.addEventListener('keydown', function(event) {
if (event.key === ' ') { // 当按下空格键时切换几何体
switchGeometry();
}
});
// 渲染函数
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
},
},
mounted() {
this.initThree();
}
}
</script>
<style scoped>
.container {
width: 1000px;
height: 660px;
margin: 10px auto;
border: 1px solid #42B983;
}
#vue-three {
width: 960px;
height: 530px;
margin: 0 auto;
border: 1px solid #42B983;
position: relative;
}
</style>
五、相关文章参考
https://dajianshi.blog.csdn.net/article/details/141935205
标签:threeJS,scene,示例,THREE,currentMesh,new,几何体 From: https://blog.csdn.net/cuclife/article/details/143405086