我无法从JSON文件中读取数据。我已经阅读了有关Stack Overflow和JSON文档的其他JSON问题,但无济于事。
我正在尝试读取要在Three.js中显示的数据。以下代码段有效:
var obj = { "points" : [
{ "vertex":[0.0,0.0,0.0] },
{ "vertex":[200.0,0.0,0.0] },
{ "vertex":[-200.0,0.0,0.0] },
{ "vertex":[0.0,100.0,0.0] },
{ "vertex":[0.0,-100.0,0.0] },
{ "vertex":[0.0,0.0,300.0] },
{ "vertex":[0.0,0.0,-300.0] },
{ "vertex":[75.0,75.0,75.0] },
{ "vertex":[50.0,50.0,50.0] },
{ "vertex":[25.0,25.0,25.0] } ]};
var geometry = new THREE.Geometry();
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = obj.points[i].vertex[0];
vertex.y = obj.points[i].vertex[1];
vertex.z = obj.points[i].vertex[2];
geometry.vertices.push( vertex );
}
它读取点并且点进一步向下渲染。我在index.html旁边有一个名为
的文件test.json
它包含以下内容:
{ "points" : [
{ "vertex":[0.0,0.0,0.0] },
{ "vertex":[200.0,0.0,0.0] },
{ "vertex":[-200.0,0.0,0.0] },
{ "vertex":[0.0,100.0,0.0] },
{ "vertex":[0.0,-100.0,0.0] },
{ "vertex":[0.0,0.0,300.0] },
{ "vertex":[0.0,0.0,-300.0] },
{ "vertex":[75.0,75.0,75.0] },
{ "vertex":[50.0,50.0,50.0] },
{ "vertex":[25.0,25.0,25.0] }
]}
我的问题是以下不起作用(即不显示点数):
var geometry = new THREE.Geometry();
var obj2 = jQuery.getJSON('test.json');
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = obj2.points[i].vertex[0];
vertex.y = obj2.points[i].vertex[1];
vertex.z = obj2.points[i].vertex[2];
geometry.vertices.push( vertex );
}
这些文件位于我的保管箱的公共文件夹中,并且从公共链接查看,即使如此,以防万一我使用--allow-files-access-from-files标志运行chrome。
更新
我的关键错误是没有处理getJSON函数回调中的顶点。我的第二个错误是假设在回调中将顶点添加到几何堆栈就足够了。实际上我必须从几何体创建对象并将其添加到场景中才能工作。非常感谢大家的帮助。
$.getJSON('test.json', function(obj2) {
var geometry = new THREE.Geometry();
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = obj2.points[i].vertex[0];
vertex.y = obj2.points[i].vertex[1];
vertex.z = obj2.points[i].vertex[2];
geometry.vertices.push( vertex );
}
vc1 = geometry.vertices.length;
object = new THREE.ParticleSystem( geometry, shaderMaterial );
object.dynamic = true;
var vertices = object.geometry.vertices;
var values_size = attributes.size.value;
var values_color = attributes.ca.value;
for( var v = 0; v < vertices.length; v ++ ) {
values_size[ v ] = 50;
values_color[ v ] = new THREE.Color( 0xffffff );
}
scene.add( object );
});
答案 0 :(得分:5)
阅读getJSON的文档,这是一个异步调用!
您需要将for循环放入回调中。
答案 1 :(得分:1)
我认为你应该这样做
$.getJSON('test.json', function(obj2) {
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = obj2.points[i].vertex[0];
vertex.y = obj2.points[i].vertex[1];
vertex.z = obj2.points[i].vertex[2];
geometry.vertices.push( vertex );
}
});
EDIT1 错字
答案 2 :(得分:0)
好像很小的错误。 你可以这样做:
1)检查你的html页面中是否引用了test.json?
2)使用firebug(控制台选项卡)检查getJson方法
返回的确切内容