javascript - 如何将数据库中的数据应用于 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 的新手,这让我很困惑。
解决方案
我认为您混淆了data
. 有时你把 is 当作一个对象,有时你把它当作一个数组。
例如,如果您data.length
在 for() 循环中使用,则 thendata
是一个数组。您不能访问数组的.description
or ,但也许您可以在数组内的每个元素中访问它们:等....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)
}
推荐阅读
- python-3.x - Facets 子类型和类型结果未在 Elasticsearch 中一起显示
- ios - AVPlayerItem seekableTimeRanges 没有跟上播放列表文件中的最新块
- jmeter - 为什么 IF 控制器后 HTTP 请求不执行
- python - 将列表作为参数传递,但保留默认值
- javascript - Javascript调用堆栈是否存在于堆中?
- c# - 尽管设置了 minLevel,但 NLog 在库项目的所有级别上进行日志记录
- python - 如何解决 Django 中的 MissingRate 错误?
- javascript - 尽管有 withCredentials: true 但没有设置 Cookie
- javascript - 如何在 CSS 中重新创建此切换?
- docker - docker push 给我那个错误:“带有标签的图像在本地不存在”