Search code examples
javascriptthree.jshtml5-canvasrenderer

Are there pros & cons in rendering three.js on <canvas> instead of <div>?


I've seen in three.js examples using:

renderer = new THREE.WebGLRenderer( { canvas: document.querySelector( 'canvas' ) } );

which refers to a <canvas></canvas> element.

That is in contrast to:

renderer = new THREE.WebGLRenderer();
var container = getelementbyid("container"):
container.appendChild( renderer.domElement );

which refers to a <div></div> element.

In both cases WebGLRenderer is used, and canvas can also be styled, so is it exactly the same, or are there any pros and cons, like devices' support, performance and limitations -why one should chose one vs the other?


Solution

  • The first option is intended for users who want to explicitly pass in a custom canvas element. If you don't do this, WebGLRenderer will create an internal canvas in its constructor (see here).

    In both cases renderer.domElement represents the drawing surface and is just a reference to a canvas element. container.appendChild( renderer.domElement ); is necessary to append the internal canvas to the DOM. But you don't necessarily have to use a container element for this. document.body.appendChild( renderer.domElement ) is sufficient in most cases.