如何解决如何逐列迭代数据并将它们提供给一个three.js 3D模型?
我正在使用three.js 开发一个3D 模型,该模型使用加速度计和陀螺仪显示车辆的位置和方向。 我有一个 xlsx 文件,其中包含 x、y、z、滚动、偏航和俯仰的数据。到目前为止,我已经在随机生成的数据上运行了 3D 模型,另一方面,我开发了读取 xlsx 文件并显示数据的代码。
我的计划是,在读取 xlsx 文件后,我遍历 x 列、y 列等,并在 3D 模型代码中使用它们(用真实数据替换随机生成的数据)。
我的 xlsx 数据格式如下:
这是文件:
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 的半初学者,所以我感谢您对指导解决此问题的任何帮助。
解决方法
- 浏览器无法处理
.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
}
- 渲染时通过积分加速度计算当前位置。
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 举报,一经查实,本站将立刻删除。