通过X3Dom使用X3D时,有时候我想动态添加对象。作为一个例子,我可能有一个像下面这样的函数来添加一行:
function add_line(lineString) {
var lineString = lineString || random_line();
var orbit = $("<shape></shape>");
scene.append(orbit);
var indexedLineSet = $("<IndexedLineSet></IndexedLineSet>");
orbit.append(indexedLineSet).attr('coordIndex', '0 1');
var coordinate = $("<coordinate></coordinate>");
coordinate.attr('point', lineString);
indexedLineSet.append(coordinate)
}
在此代码中,scene
是现有的X3D场景,random_line
是一个生成定义随机行的字符串的函数,我使用JQuery操作场景。在页面加载时调用函数时,它可以正常工作。然而,当响应按钮按下来调用该功能时,该线条不会出现,尽管它被添加到场景中。
注意:
IndexedLineScene
似乎正确添加到场景中;它只是没有出现在图像中。答案 0 :(得分:1)
如果您打开开发者控制台,则可以找到:
x3dom.js:3014 Uncaught TypeError: Cannot read property 'getPoints' of null_
buildGeometry @ x3dom.js:3014
nodeChanged @ x3dom.js:3046
x3dom.NodeNameSpace.setupTree @ x3dom.js:2744
onNodeInserted @ x3dom.js:1100
(anonymous function) @ jquery-1.12.4.min.js:3
Ha @ jquery-1.12.4.min.js:3
append @ jquery-1.12.4.min.js:3
add_line @ IndexedLineSet-Test.html:76
(anonymous function) @ IndexedLineSet-Test.html:90
dispatch @ jquery-1.12.4.min.js:3
r.handle @ jquery-1.12.4.min.js:3
在调查原始代码的第76行后,您会发现必须更改添加点的顺序并添加索引:
var indexedLineSet = $("<IndexedLineSet></IndexedLineSet>");
var coordinate = $("<coordinate></coordinate>");
coordinate.attr('point', lineString);
indexedLineSet.append(coordinate);
orbit.append(indexedLineSet).attr('coordIndex', '0 1');
在初始加载时它适用于您,因为您在X3DOM准备就绪之前构建了x3d,检查此调用何时出现(在您对add_line
的调用完成后):
x3dom.runtime.ready = function() {
console.log('ready');
};
这意味着尚未设置所有事件和侦听器。但是稍后当您单击该按钮时,X3DOM已完全初始化。因此,它可以在您将轨道附加到场景后立即收听所有事件并触发onNodeInserted
事件。另一种解决方案是在函数结束时调用此函数: