title: How to render a webgl in a responsive iframe?
body: <p>I'm using <a href="http://threejs.org/" rel="nofollow">ThreeJS</a> to paint 3D experiments of planets in a <code>responsive</code> iframe. Here's an illustration of <a href="https://bubbl.in/book/responsive-webgl-test-by-marvin-danig/1" rel="nofollow">Earth</a>, for example.</p>
  
  <p>This works fine on <code>DOMContentLoaded</code>, but not onresize. The scene is cut off or remains at (0,0) top-left as per its first render. Note, this is the recommended behavior according to <a href="http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html" rel="nofollow">webgl anti patterns</a>.</p>
  
  <p>But I want to scale the planet according to the new size of the iframe, both when the window is resized or when <code>orientation</code> changes (and leads to a resize). Essentially, to make it cross-platform and responsive.</p>
  
  <p>I have a few ideas to make this work:</p>
  
  <p>Use <code>innerWidth/innerHeight</code>, even though it is an <a href="http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html" rel="nofollow">anti-pattern</a>, but can work if we dispose() and repaint the scene with new height &amp; width of the iframe.</p>
  
  <p>Ensure the disposition and repaint is carried out efficiently, i.e. setTimeout and detect <code>resizeFinish()</code> like so:</p>
  
  <pre><code>function resizeFinish() {
    width = window.clientWidth;
    height = window.clientHeight;
  
    renderer.setSize(width, height);
    render();
  
    if (scene) {
      while (scene.children.length &gt; 0) {
        scene.remove(scene.children[scene.children.length - 1]);
      }
  
      // cleanup without calling render (data needs to be cleaned up before a new scene can be generated)
      renderer.dispose(scene.children);
    }
  
    alertSize();
  
  
  }
  window.onresize = function() {
    clearTimeout(doit);
    doit = setTimeout(function() {
      resizeFinish();
    }, 1000);
  };
  
  
  function render() {
    controls.update();
    sphere.rotation.y += 0.003;
    clouds.rotation.y += 0.005;
    requestAnimationFrame(render);
    renderer.render(scene, camera);
  }
  </code></pre>
  
  <p>Is this good enough?</p>