如何逐列迭代数据并将它们提供给一个three.js 3D模型?

如何解决如何逐列迭代数据并将它们提供给一个three.js 3D模型?

我正在使用three.js 开发一个3D 模型,该模型使用加速度计和陀螺仪显示车辆的位置和方向。 我有一个 xlsx 文件,其中包含 x、y、z、滚动、偏航和俯仰的数据。到目前为止,我已经在随机生成的数据上运行了 3D 模型,另一方面,我开发了读取 xlsx 文件并显示数据的代码。

我的计划是,在读取 xlsx 文件后,我遍历 x 列、y 列等,并在 3D 模型代码中使用它们(用真实数据替换随机生成的数据)。

我的 xlsx 数据格式如下:

enter image description here

这是文件:

Click here to download the data

这是我从 xlsx 文件中读取的代码:

var parser = new (require('simple-excel-to-json').XlsParser)();
var doc = parser.parseXls2Json('data/TestingWithThresholdXLSX.xlsx');
// convert json to string
var docToString = JSON.stringify(doc)
// parsing the JSON string text into a javascript Object
var json = JSON.parse(docToString);
// Loop through the json string
var text;
for (i = 0; i < 100; i++) {
    text = json[0][i]["TimeId"];
    console.log(text)
  }

这是我制作 3D 模型的代码:

HTML

<!DOCTYPE html>
<html>
 <head>
   <meta charset="UTF-8">
   <link rel="stylesheet" type="css" href="css/style.css">
   <script src="https://threejs.org/build/three.min.js"></script>
   <script src= "https://threejs.org/examples/js/controls/OrbitControls.js"></script>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
   <script src="https://requirejs.org/docs/release/2.3.6/comments/require.js" type="text/javascript"></script>
   <script type="module"> import * as THREE from "https://threejsfundamentals.org/threejs/resources/threejs/r122/build/three.module.js"</script>
  </head>

<h1 style="color:red">3D Model Rotation and Translation</h1>
<body>
 <canvas id="canvas" width="1500" height="800" style="border:1px solid #000000;"></canvas>
 <div id="accelPanel"></div>
</body>
<script src="js/index.js"></script>
</html>

Javascript

function main() {
  const canvas = document.querySelector('#canvas');
  const accelPanel = document.querySelector('#accelPanel');
  const renderer = new THREE.WebGLRenderer({canvas});
  var context = canvas.getContext("2d");
  
  const fov = 60;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 2000;
  const camera = new THREE.PerspectiveCamera(fov,aspect,near,far);
  camera.position.set(0,50,1.5);
  camera.up.set(0,1);
  camera.lookAt(0,0);
  
  const scene = new THREE.Scene();
  {
    const color = 0xFFFFFF;
    const intensity = 1;
    const light = new THREE.PointLight(color,intensity);
    scene.add(light);
  }
  // an array of objects who's rotation to update
  const objects = [];
  const radius = 3;
  const widthSegments = 3;
  const heightSegments = 3;
  const sphereGeometry = new THREE.BoxGeometry(radius,widthSegments,heightSegments);
  const sunMaterial = new THREE.MeshBasicMaterial({color: "green",wireframe: false}); 
  const sunMesh = new THREE.Mesh(sphereGeometry,sunMaterial);

  var cubeAxis = new THREE.AxesHelper(10);
    sunMesh.add(cubeAxis);

  sunMesh.scale.set(2,2,2);
  scene.add(sunMesh);
  objects.push(sunMesh);

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width,height,false);
    }
    return needResize;
  }
  
  function render(speed) {
    speed *= 0.001;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    /* This is where I assume the data should be placed*/
    objects.forEach((obj) => {
      obj.rotation.x = speed+1;
      obj.rotation.y = speed+2;
      obj.rotation.z = speed+34;
      obj.position.x = speed+1;
      obj.position.y = speed+2;
      obj.position.z = speed+2;
      console.log(obj.position.y);
    });   
    renderer.render(scene,camera);
    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);
}
main();

您可以找到工作代码 JSFiddle

我尝试将数据读取器代码放在 3D 模型的 javascript 代码中,特别是在 objects.forEach((obj) => 之后,但它从未奏效,而且我是 javascript 的半初学者,所以我感谢您对指导解决此问题的任何帮助。

解决方法

  1. 浏览器无法处理 .xlsx 文件。事先将其解析为 JSON 文件(使用 node.js)。
    此脚本从同一目录中获取 data.xlsx 并将其输出到 data.json(您可以自由地使其在文件大小方面更高效)。
const fs = require('fs')
const path = require('path')
const { XlsParser } = require('simple-excel-to-json')

const SECONDS_PER_DAY = 24 * 60 * 60

const json = (new XlsParser()).parseXls2Json(path.resolve(__dirname,'data.xlsx'));
const data = json[0].map((item) => ({
    time: item.TimeId * SECONDS_PER_DAY,rotX: deg2Rad(item.Gyro_X),rotY: deg2Rad(item.Gyro_Y),rotZ: deg2Rad(item.Gyro_Z),accX: item.Accelero_X,accY: item.Accelero_Y,accZ: item.Accelero_Z,}))
fs.writeFileSync(path.resolve(__dirname,'data.json'),JSON.stringify(data))

function deg2Rad(angle) {
    return angle * Math.PI / 180
}
  1. 渲染时通过积分加速度计算当前位置。
let currentIndex = 0
let time = data[currentIndex].time
let velocity = new THREE.Vector3()
requestAnimationFrame(render);

function render(dt) {
    dt *= 0.001 // in seconds
    time += dt
    document.querySelector("#time").textContent = time.toFixed(2)

    // Find datapoint matching current time
    while (data[currentIndex].time < time) {
        currentIndex++
        if (currentIndex >= data.length) return
    }
    const { rotX,rotY,rotZ,accX,accY,accZ } = data[currentIndex]
    const acceleration = new THREE.Vector3(accX,accZ)
    object.rotation.set(rotX,rotZ)
    object.position.add(velocity.clone().multiplyScalar(dt)).add(acceleration.clone().multiplyScalar(0.5 * dt ** 2))
    velocity.add(acceleration.clone().multiplyScalar(dt))

    resizeToClient();
    renderer.render(scene,camera);
    requestAnimationFrame(render);
}

您可以在我创建的 GitHub 存储库中找到所有内容: https://github.com/Josef37/threejs-from-xlsx

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-