How can I put my scene inside a html div?

I found in another forum the last 6 lines of the code to fix the problem but when I run it, the scene doesn´t shows and I get the following message in the console:

“Uncaught TypeError: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’.”

Thank you in advance!

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
    camera.position.z = 400;
    scene = new THREE.Scene();
    const geometry = new THREE.IcosahedronGeometry( 170, 0 );
    const material =  new THREE.MeshStandardMaterial( {color: 0xabdec6} );

    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );
    const light = new THREE.AmbientLight( 0xd4d4d4 ); 
    scene.add( light );
    const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
    scene.add( directionalLight );

    container = document.getElementById( 'canvas' );
    document.body.appendChild( container );
    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );
}

There should be no problem to put the <canvas> inside a <div> or other tags, like <td>, <p>, etc. Most likely there is some problem with your JS or HTML code. According to the posted fragment, you try to put your scene in a tag like this:

<div id="canvas">...</div>

Possible reasons (this is just a guess):

  • There is no such tag in your HTML – check whether document.getElementById( 'canvas' ) returns a valid object.
  • There is such tag, but it is rather small (e.g. height is 1 line), so the Three.js’s area it outside the <div> – note that the renderer is set to be as big as the whole window (renderer.setSize), so your <div> should be that big too.
  • Something else, but it would help a lot if you post online example, that can be run and modified.

Meanwhile, see this example:

https://codepen.io/boytchev/full/JjaBbra

image

You can also have a look at this suggestion.

Thank you so much! I’ll work from your example

1 Like