首页 > 解决方案 > 如何将数据库中的数据应用于 Three.js 交互式对象

问题描述

我正在尝试为数据库中的每个条目呈现一个对象,并根据每个对象的相关数据库条目将 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 的新手,这让我很困惑。

标签: javascriptjsonthree.jsdata-visualization

解决方案


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

例如,如果您data.length在 for() 循环中使用,则 thendata是一个数组。您不能访问数组的.descriptionor ,但也许您可以在数组的每个元素中访问它们:等....titledata[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)
}

推荐阅读