我正在尝试为数据库中的每个条目呈现一个对象,并根据它们的相关数据库条目将诸如 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' 似乎是要走的路。
目前我可以将鼠标悬停在对象上,它们会通过 Raycasting 改变颜色。将来,一旦我克服了这个障碍,我将创建一种方法来在对象悬停时查看标题等文本数据,并在单击时指向 URL。
我是three.js的新手,这让我感到困惑。
我认为你混淆了data
. 有时将 is 视为对象,有时将其视为数组。
例如,如果您data.length
在 for() 循环中使用,则data
是一个数组。您无法访问.description
或.title
数组的,但也许你可以访问它们的每个元素内内与阵列: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)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句