How to change a ThreeJS scene

I was playing with ThreeJS to make a tiny game prototype and I didn’t know how to change a ThreeJS scene in order to restart the level, change it or load a game.

It’s not so hard but you should know a few points.

Prerequisites

As you know, ThreeJS links a scene to a DOM element and you can have only 1 scene.

Probably you would have it with a UI, for example:

<div id="game">
  <span id="health" 
    style="position: absolute; top: 5%; left: 5%;">
  </span>
</div>

And your scene uses it as container.

Ok, we can have only 1 scene and we already have the UI in the container.

Concept

So a solution would be to get and use a copy of the container:

  • with the UI
  • with a different ID
  • without threeJS bindings or events
  • and use it as container for the scene.

Solution

In your game controller, where you init the game, add:

$('#game').clone() 
  .off() 
  .attr('id','game_scene') 
  .prependTo('body');

Yeah, I used jQuery, it’s not mandatory, you can do it with plain Javascript but I already used it for animations and I reused it for a quick way to do the next points, let me comment each function:

  • clone() Get a copy of the DOM element
  • off() Remove all events attached
  • attr() Set a different ID
  • prependTo() Add the copy to the body

Then, when you need to change your scene like where you reset the level, change it or whatever, add:

$('#game_scene').remove(); 
var copy = $('#game').clone() 
  .off() 
  .attr('id','game_scene'); 
copy.prependTo('body');

Finally, you should use it in your scene

var game_scene = document.getElementById('game_scene'); 
game_scene.appendChild(scene.renderer.domElement);

That’s all. It should works.

Leave a comment if you need help, have a question or any suggestion! 🙂