我是Three.js的新手,所以我可能犯了一些愚蠢的错误。这是我的代码,我想使用来自.k文件的坐标和表面信息来构建几何。我尝试打印geometry.vertices和geometry.faces,它们看起来都正确,我也尝试更改相机位置,但是屏幕上没有任何显示。请帮助!
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var geometry = new THREE.Geometry();
var map = {}; // node id map to index geometry vertices
// reading in k file line by line
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
var node_flag = false, element_flag = false;
reader.onload = function(progressEvent){
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; ++line){
if(!node_flag && lines[line].substr(0,5) == "*NODE") {
node_flag = true;
continue;
}
if(lines[line].substr(0,8) == "$# title")
node_flag = false;
else if(lines[line].substr(0,14) == "*ELEMENT_SHELL") {
element_flag = true;
continue;
}
else if(lines[line].substr(0,14) == "*ELEMENT_SOLID")
break;
// start reading nodes and build vectors
if(node_flag) {
// tokenize a line into array of strings
let data = lines[line].match(/\S+/g);
map[data[0]] = geometry.vertices.length-1;
geometry.vertices.push((new THREE.Vector3(+data[1], +data[2], +data[3])));
}
// start reading element shell and building surfaces
if(element_flag){
// tokenize a line into array of strings
let data = lines[line].match(/\S+/g);
geometry.faces.push(new THREE.Face3(map[data[2]], map[data[3]],map[data[4]]));
// geometry.faces.push(new THREE.Face3(map[data[2]]), map[data[5]],map[data[4]]);
}
}
}
reader.readAsText(file);
finish_loading();
}
var material = new THREE.MeshBasicMaterial( { color: 0xffffff } );
var cube;
// test
var axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
//test
camera.position.z = 100;
function animate() {
requestAnimationFrame( animate );
cube.rotation.x += 0.1;
//cube.rotation.y += 0.01;
// cube.rotation.z += 0.01;
renderer.render( scene, camera );
}
function finish_loading(){
cube = new THREE.Mesh( geometry, material );
scene.add( cube );
animate();
}
<!DOCTYPE html>
<html>
<head>
<title>MDP Web-tool</title>
<!--js library-->
<link type="text/css" href="css/style.css">
<script src = "js/library/three.js"></script>
<script src="js/library/node_modules/hashmap/hashmap.js"> </script>
</head>
<body>
<canvas id = "myCanvas"></canvas>
<input type="file" id="file">
<!--custom js files-->
<script src="js/model.js"></script>
</body>
</html>
答案 0 :(得分:0)
您在finish_loading()
回调之外调用onload
。它会在您的.onload
回调触发之前很久就被执行。将其放在for循环之后。