gpt4 book ai didi

javascript - 从 JSON 文件中读取点数组

转载 作者:行者123 更新时间:2023-11-29 16:16:11 27 4
gpt4 key购买 nike

我在从 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 );
}

这些文件位于我的保管箱的公共(public)文件夹中,可以从公共(public)链接查看,即使如此,以防万一我使用 --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 );
});

最佳答案

阅读 getJSON 的文档, 是异步调用!

你需要在回调中加入for循环。

关于javascript - 从 JSON 文件中读取点数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15362177/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com