ThreeJs功能演示——几何体操作导入导出

server/2025/1/19 5:25:19/

1、内部创建几何体导出编辑能力

1)支持内部创建的面、正方体、球体

内部创建物体时,如果是三维物体,要创建集合形状geometry,和对应的材质material。再一起创建一个三维物体。

javascript">	// 存储创建的几何体列表const geometries = [];createPlane()createCube()createSphere()addGUIForGeometry(geometries)// 几何体创建函数function createPlane() {const geometry = new THREE.PlaneGeometry(1,1);const material = new THREE.MeshBasicMaterial({color:0xffff00, side:THREE.DoubleSide})const plane = new THREE.Mesh(geometry, material)plane.name = "Plane";plane.position.set(-1, -1, -1)scene.add(plane)geometries.push(plane)return plane;}// 创建正方体function createCube() {const geometry = new THREE.BoxGeometry(1, 1, 1 );const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );const cube = new THREE.Mesh( geometry, material );cube.name = 'Cube';scene.add( cube );geometries.push(cube);return cube;}// 创建球体function createSphere() {const geometry = new THREE.SphereGeometry( 1, 32, 32 );const material = new THREE.MeshBasicMaterial( {color: 0x0000ff} );const sphere = new THREE.Mesh( geometry, material );sphere.name = 'Sphere';sphere.position.set(2,2,2)scene.add( sphere );geometries.push(sphere);return sphere;}

2)支持几何体的位置、角度、比例调整

通过GUI控制器调整创建物体的位置、角度、放大比例信息。

javascript">	// GUI控制器function addGUIForGeometry(geometryArr) {const gui = new GUI();gui.add({x:0}, 'x', -10, 10).name('Position X').onChange((value)=>{for (let element of geometryArr) {console.log(element.position)element.position.set(value, element.position.y, element.position.z)}animate()});gui.add({scale:1}, 'scale', 0.1, 10).name('Scale').onChange((value)=>{for (let element of geometryArr) {element.scale.set(value, value, value)}animate()});gui.add({rotateX:0}, "rotateX",  -Math.PI, Math.PI).name("Rotate X").onChange((value)=>{for (let element of geometryArr) {element.rotation.set(value, element.rotation.y, element.rotation.z)}animate()})gui.open();}

3)支持几何体批量导出、重新导入

将3D物体的位置、形状、角度、放大序列化到json文件,支持导出。

导入时,根据物体的类型分别创建3D模型

javascript">	// 导入几何体function importGeometries() {const input = document.createElement('input');input.type = 'file';input.accept = '.json';input.addEventListener('change', (event) => {const file = event.target.files[0];if (file) {const reader = new FileReader();reader.onload = (e) => {const geometriesData = JSON.parse(e.target.result);geometriesData.forEach(data => {let geometry;let material;switch (data.type) {case 'Mesh':switch (data.name) {case 'Plane':geometry = new THREE.PlaneGeometry(data.geometryData.vertices, data.geometryData.indices);material = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide });break;case 'Cube':geometry = new THREE.BoxGeometry(data.geometryData.vertices, data.geometryData.indices);material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });break;case 'Sphere':geometry = new THREE.SphereGeometry(data.geometryData.vertices, data.geometryData.indices);material = new THREE.MeshBasicMaterial({ color: 0x0000ff });break;}const mesh = new THREE.Mesh(geometry, material);mesh.name = data.name;mesh.position.fromArray(data.position);mesh.rotation.fromArray(data.rotation);mesh.scale.fromArray(data.scale);scene.add(mesh);geometries.push(mesh);break;}});};reader.readAsText(file);}});input.click();}

2、整体代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Three.js 几何体操作示例</title><style>body { margin: 0; overflow: hidden; }#camera-info {position: absolute;top: 10px;left: 10px;background-color: rgba(0, 0, 0, 0.5);color: white;padding: 10px;font-family: Arial, sans-serif;}</style>
</head>
<body>
<div id="camera-info"></div>
<script type="importmap">{"imports": {"three": "./three.js-master/build/three.module.js","three/addons/": "./three.js-master/examples/jsm/"}}
</script>
<script type="module">import * as THREE from "three"import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import { GUI } from 'three/addons/libs/lil-gui.module.min.js';// 1) 创建画布const scene = new THREE.Scene();scene.background = new THREE.Color( 0xa0a0a0 );const renderer = new THREE.WebGLRenderer();renderer.setSize(window.innerWidth, window.innerHeight);document.body.appendChild(renderer.domElement);// 2) 设置 camera 位置,朝向角度const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);camera.position.set(0, 0, 20); // 设置相机位置camera.lookAt(scene.position); // 让相机朝向场景中心// 设置控制轨道const controls = new OrbitControls( camera, renderer.domElement );controls.target.set( 0, 0.1, 0 );controls.update();controls.minDistance = 0.5;controls.maxDistance = 1000;controls.maxPolarAngle = 0.5 * Math.PI;// 5) 支持动态显示摄像头位置、角度、缩放信息const cameraInfo = document.getElementById('camera-info');function updateCameraInfo() {cameraInfo.innerHTML = `摄像头信息:<br>位置: (${camera.position.x.toFixed(2)}, ${camera.position.y.toFixed(2)}, ${camera.position.z.toFixed(2)})<br>角度: (${camera.rotation.x.toFixed(2)}, ${camera.rotation.y.toFixed(2)}, ${camera.rotation.z.toFixed(2)})<br>缩放: ${camera.zoom.toFixed(2)}`;}updateCameraInfo();// 渲染循环function animate() {requestAnimationFrame(animate);updateCameraInfo();renderer.render(scene, camera);}animate();// 存储创建的几何体列表const geometries = [];createPlane()createCube()createSphere()addGUIForGeometry(geometries)// 几何体创建函数function createPlane() {const geometry = new THREE.PlaneGeometry(1,1);const material = new THREE.MeshBasicMaterial({color:0xffff00, side:THREE.DoubleSide})const plane = new THREE.Mesh(geometry, material)plane.name = "Plane";plane.position.set(-1, -1, -1)scene.add(plane)geometries.push(plane)return plane;}// 创建正方体function createCube() {const geometry = new THREE.BoxGeometry(1, 1, 1 );const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );const cube = new THREE.Mesh( geometry, material );cube.name = 'Cube';scene.add( cube );geometries.push(cube);return cube;}// 创建球体function createSphere() {const geometry = new THREE.SphereGeometry( 1, 32, 32 );const material = new THREE.MeshBasicMaterial( {color: 0x0000ff} );const sphere = new THREE.Mesh( geometry, material );sphere.name = 'Sphere';sphere.position.set(2,2,2)scene.add( sphere );geometries.push(sphere);return sphere;}// GUI控制器function addGUIForGeometry(geometryArr) {const gui = new GUI();gui.add({x:0}, 'x', -10, 10).name('Position X').onChange((value)=>{for (let element of geometryArr) {console.log(element.position)element.position.set(value, element.position.y, element.position.z)}animate()});gui.add({scale:1}, 'scale', 0.1, 10).name('Scale').onChange((value)=>{for (let element of geometryArr) {element.scale.set(value, value, value)}animate()});gui.add({rotateX:0}, "rotateX",  -Math.PI, Math.PI).name("Rotate X").onChange((value)=>{for (let element of geometryArr) {element.rotation.set(value, element.rotation.y, element.rotation.z)}animate()})gui.open();}function handleKeyDown(event) {switch (event.key) {case 'e':exportToJSON(geometries)break;case 'r':clearGeometries(geometries)break;case 'i':importGeometries(geometries)break;}}document.addEventListener('keydown', handleKeyDown);function exportToJSON(geometryList) {const geometriesData = geometryList.map(geometry => {return {name: geometry.name,position: geometry.position.toArray(),rotation: geometry.rotation.toArray(),scale: geometry.scale.toArray(),// 根据几何体类型添加更多特定信息type: geometry.type,geometryData: geometry.geometry.toJSON()};});const blob = new Blob([JSON.stringify(geometriesData)], { type: 'application/json' });const url = URL.createObjectURL(blob);const a = document.createElement('a');a.href = url;a.download = 'geometries.json';document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);}// 清除几何体function clearGeometries(geoArr) {geometries.forEach(geometry => scene.remove(geometry));geometries.length = 0;}// 导入几何体function importGeometries() {const input = document.createElement('input');input.type = 'file';input.accept = '.json';input.addEventListener('change', (event) => {const file = event.target.files[0];if (file) {const reader = new FileReader();reader.onload = (e) => {const geometriesData = JSON.parse(e.target.result);geometriesData.forEach(data => {let geometry;let material;switch (data.type) {case 'Mesh':switch (data.name) {case 'Plane':geometry = new THREE.PlaneGeometry(data.geometryData.vertices, data.geometryData.indices);material = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide });break;case 'Cube':geometry = new THREE.BoxGeometry(data.geometryData.vertices, data.geometryData.indices);material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });break;case 'Sphere':geometry = new THREE.SphereGeometry(data.geometryData.vertices, data.geometryData.indices);material = new THREE.MeshBasicMaterial({ color: 0x0000ff });break;}const mesh = new THREE.Mesh(geometry, material);mesh.name = data.name;mesh.position.fromArray(data.position);mesh.rotation.fromArray(data.rotation);mesh.scale.fromArray(data.scale);scene.add(mesh);geometries.push(mesh);break;}});};reader.readAsText(file);}});input.click();}
</script>
</body>
</html>


http://www.ppmy.cn/server/159550.html

相关文章

使用Selenium进行网页自动化测试

# 导入Selenium的webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys import time # 创建WebDriver对象&#xff0c;指定使用Chrome浏览器和浏览器驱动的路径 driver webdriver.Chrome(executable_path/path/to/chromedriver) # …

《自动驾驶与机器人中的SLAM技术》ch9:自动驾驶车辆的离线地图构建

目录 1 点云建图的流程 2 前端实现 2.1 前端流程 2.2 前端结果 3 后端位姿图优化与异常值剔除 3.1 两阶段优化流程 3.2 优化结果 ① 第一阶段优化结果 ② 第二阶段优化结果 4 回环检测 4.1 回环检测流程 ① 遍历第一阶段优化轨迹中的关键帧。 ② 并发计算候选回环对…

【RabbitMQ】rabbitmq广播模式的使用

前言&#xff1a; 项目需要同步另一个系统的数据&#xff0c;对方系统采用MQ的发布/订阅模式方便我们同步数据&#xff0c;即当对方系统中的某条数据修改后&#xff0c;会向绑定他们交换机的每一个队列发布消息。消费者&#xff08;即我们&#xff09;监听到消息变动&#xff0…

机器学习与深度学习在气象中的应用

专题一 Python和科学计算基础1.1 Python入门和安装 1.1.1 Python背景及其在气象中的应用 1.1.2 Anaconda解释和安装以及Jupyter配置 1.1.3 Python基础语法 1.2 科学数据处理基础库 1.2.1 Numpy库 1.2.2 Pandas库 1.2.3 Scipy库 1.2.4 Matplotlib和Cartopy库 1.2.5 常用数据格式…

cmake + vscode + mingw 开发环境配置

1.软件准备 准备如下软件&#xff1a; mingw64&#xff08;安装完成之后检测是否有环境变量&#xff0c;如果没有需要配置&#xff09; cmake&#xff08;安装完成之后检测是否有环境变量&#xff0c;如果没有需要配置&#xff09; vscode&#xff08;安装CMake插件&#xff0…

深度剖析RabbitMQ:从基础组件到管理页面详解

文章目录 一、简介二、Overview2.1 Overview->Totals2.2 Overview->Nodesbroker的属性2.3 Overview->Churn statistics2.4 Overview->Ports and contexts2.5 Overview->Export definitions2.6 Overview->Import definitions 三、Connections连接的属性 四、C…

如何在亚马逊云科技上消除无服务器网页应用冷启动时间(下篇)

背景 我们在云端搭建无服务器&#xff08;serverless&#xff09;开发架构时&#xff0c;经常会被冷启动&#xff08;cold start&#xff09;带来的应用延迟所困扰。冷启动是指当无服务器资源在一段时间内未被调用&#xff0c;或需要扩展以处理新请求时&#xff0c;系统需要初…

阀井可燃气体监测仪,开启地下管网安全新篇章-旭华智能

在城市的脉络中&#xff0c;地下管网犹如隐秘的动脉&#xff0c;支撑着现代生活的运转。而在这庞大网络的关键节点上&#xff0c;阀井扮演着不可或缺的角色。然而&#xff0c;由于其密闭性和复杂性&#xff0c;阀井内部一旦发生可燃气体泄漏&#xff0c;将对公共安全构成严重威…