3

I'm trying to build an AFrame app where users can click on something and a new scene will show up. From there, the user can click on something else, etc. This scene's data is taken from an API, so it's tough to know all possible scenes the user can encounter.

With this in mind, how would you go about modifying the AFrame scene during runtime? Apparently modifying the DOM doesn't work, but if there is a way to have AFrame re-render the scene at a certain time, that would be awesome. If you think there's another way to approach this, I'd love to hear it. Thanks!

hyperdo
  • 417
  • 1
  • 6
  • 11

2 Answers2

8

Just for future reference since you have already solved your issue, you can use the normal JS DOM API:

var el = document.createElement('a-entity');
document.querySelector('a-scene').appendChild(el);
ngokevin
  • 12,980
  • 2
  • 38
  • 84
4

You can indeed modify DOM during runtime and it will affect the scene. Here is an example of adding a new object using jQuery taken from this project:

function appendObject(id, file, scale, position, rotation, scale) {
        $('<a-obj-model />', {
          id: id,
          class: 'city object children',
          position: position,  // doesn't seem to do anything, known issue
          scale: scale,
          rotation: rotation,
          file: file,
          src: '#' + file + '-obj',
          mtl: '#' + file + '-mtl',
          appendTo : $('#city')
        });
       document.getElementById(id).setAttribute("position", position); // this does set position as a workaround
      }

And here is an example of removing an object:

 onMenuDown: function () {
        previousObject = document.querySelector("#object" + (objectCount - 1));
        previousObject.parentNode.removeChild(previousObject);
        objectCount -= 1;
        if(objectCount == -1) {objectCount = 0};
  },
Kieran F.
  • 567
  • 4
  • 16
  • Hmmm... for me, when I update the DOM, I get [this error](http://imgur.com/a/I8pfi) for every object I try to add. Do you know what could be causing this" – hyperdo Dec 26 '16 at 23:04
  • Actually, never mind -- I was appending after the tag. It works now! Thanks for your help; will mark as accepted. – hyperdo Dec 26 '16 at 23:19
  • Kevin's answer below is better. Here is a section of the updated docs on this topic: https://aframe.io/docs/0.7.0/introduction/javascript-events-dom-apis.html#creating-an-entity-with-createelement – Kieran F. May 20 '19 at 05:58