【问题标题】:How to apply data from a database to Three.js interactive objects如何将数据库中的数据应用于 Three.js 交互式对象
【发布时间】:2020-01-29 01:20:34
【问题描述】:

我正在尝试为数据库中的每个条目呈现一个对象,并根据每个对象的相关数据库条目将 URL、标题和描述等文本附加到每个对象。

到目前为止,我在场景中显示的 DB 中的每个条目都有一个多维数据集,但是数据记录为未定义。据我所知,我的代码应该可以工作,但实际上并没有。

  getData()

  async function getData() {
        try {
            var response = await fetch('/api/indexvr');
            var data = await response.json();


            for (var i = 0; i < data.length; i++) {
                cube = new THREE.Mesh(geometry, material.clone());
                cube.userData = {
                    id: data.id,
                    URL: `/vr/${data.id}/`,
                    title: data.title, 
                    description: data.description
                    };
                cube.position.x = i;
                scene.add(cube);
                console.log(cube.userData) 
                //group.add(data)
            }
        } catch (e) {
            console.error(e)
        }
  }

上面是获取我的 MongoDB 集合中每个条目的代码(它是文件路径和数据的列表,例如文件标题、描述和标签)。

从我发现的示例中,'userData' 似乎是要走的路。

目前我可以将鼠标悬停在对象上,它们会通过光线投射改变颜色。将来,一旦我克服了这个障碍,我将创建一种方法来查看文本数据,例如当对象悬停时的标题,并在单击时指向 URL。

我是 three.js 的新手,这让我很困惑。

【问题讨论】:

    标签: javascript json three.js data-visualization


    【解决方案1】:

    我认为您混淆了data 的结构。有时你把 is 当作一个对象,有时你把它当作一个数组。

    例如,如果您在 for() 循环中使用 data.length,则 data 是一个数组。您无法访问数组的.description.title,但也许您可以在数组的每个元素inside 内访问它们:data[0].description, data[1].description 等...

    // Create variable to make a reference
    // to the current element while looping in the array
    var arrayElement;
    
    for (var i = 0; i < data.length; i++) {
        // Get the element for this iteration
        arrayElement = data[i];
    
        cube = new THREE.Mesh(geometry, material.clone());
    
        // Now you can acces the information in the current array element
        cube.userData = {
            id: arrayElement.id,
            URL: `/vr/${arrayElement.id}/`,
            title: arrayElement.title, 
            description: arrayElement.description
        };
        cube.position.x = i;
        scene.add(cube);
        console.log(cube.userData)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多