我想阅读带有数字的文本文件,并将它们放入带有XMHLHttpRequest的矩阵
我已经使用了FileReader API,但出于某种原因,当我使用它时,我的应用程序出现了一些图形错误。
我的想法是获取文本文件中的数字并与Babylon.js一起使用,这样我就可以在画布上绘制点。
文件示例:
ng build
我想跳过所有这些第一行并开始阅读 [ARESTAS] 关键字或 TAM 关键字并将数字放入矩阵[n] [9],其中n是关键字
之后的行数前六个数字表示画布中的坐标(x,y,z),后三个表示对象颜色
这就是我对FileReader所做的:
NUM_GRUPOS 1
[GRUPO]
TAM 64
[PONTOS]
ROTULO 1
2.50000000000000E+0002 -2.00000000000000E+0002 2.00000000000000E+0001 0.00000000000000E+0000 0.00000000000000E+0000 1.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000
ROTULO 2
3.54000000000000E+0002 -2.52000000000000E+0002 3.90000000000000E+0002 1.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000 0.00000000000000E+0000
... //A bunch of other numbers
[ARESTAS]
TAM 60
2.50000000000000E+0002-2.00000000000000E+0002 2.00000000000000E+0001 3.09941176470588E+0002-1.59941176470588E+0002 8.58823529411765E+0001 0.00000000000000E+0000 0.00000000000000E+0000 1.00000000000000E+0000
答案 0 :(得分:0)
为什么要迭代行?
r.onload = function(e) {
contents = e.target.result;
var pos = contents.indexOf(keyWord) + keyWord.length; //find [ARESTAS] portion
var numbers = contents.substr(pos).trim(); //trim it from rest of file
matrix = numbers.split('\n') // get separate lines
.map(function (e) {
return e.split(' '); // split them by whitespace
})
.filter(function (e) {
return e.length > 2; // filter all unwanted lines
})
}
......甚至:
function readMatrix(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function(e) {
var contents = e.target.result;
var pos = contents.indexOf(keyWord) + keyWord.length; //find [ARESTAS] portion
var matrix = contents
.substr(pos) // get arestas section
.trim(); //trim redundant whitespace
.split('\n') // get separate lines
.slice(1) // skip TAM ### line
.map(function (e) {
return e.split(' '); // split separate lines by whitespace
}); // get final matrix
callback(matrix); // pass received data to callback
}
xhr.send();
}
document.getElementById('fileinput')
.addEventListener('change', function () {
var url = ... address of file
...
readMatrix(function (matrix) {
// we got filled matrix here
});
}, false);
答案 1 :(得分:0)
可以尝试这个作为起点
var start = contents.indexOf('[ARESTAS]');
// get rid of all before ARESTAS, then split and remove first 2 rows
var txtArr = txt.slice(start).split('\r\n').splice(2);
//trim and split each line at space and map to array of numbers
var numArr = txtArr.reduce(function(a, c){
a.push(c.trim().split(' ').map(Number))
return a
},[])
的 DEMO 强>