Putting three.js animation inside of div

You can use a pattern like the following:

<div id="canvas">

#canvas {
    background-color: #000;
    width: 200px;
    height: 200px;
    border: 1px solid black;
    margin: 100px;
    padding: 0px;
    position: static; /* fixed or static */
    top: 100px;
    left: 100px;
}

container = document.getElementById( 'canvas' );
document.body.appendChild( container );

renderer = new THREE.WebGLRenderer();
renderer.setSize( 200, 200 );
container.appendChild( renderer.domElement );

Fiddle: https://jsfiddle.net/v63Lnsd9/

Also see THREE.js Ray Intersect fails by adding div

three.js r.143


If you don't want to hardcode renderer size then below piece of code can help you.

I am dynamically calculating canvas height and width and then accordingly setting the renderer's size and camera's position.

CSS

            #canvas {
             background-color: #FFF;
             width: 200px;
             height:200px;
             border: 1px solid black;
              }

HTML

<div id="canvas"/>

JavaScript

         //Add Renderer
         renderer = new THREE.CanvasRenderer();
         var container = document.getElementById('canvas');
         var w = container.offsetWidth;
         var h = container.offsetHeight;
         renderer.setSize(w, h);
         container.appendChild(renderer.domElement);
        
        //Add Camera
        camera = new THREE.PerspectiveCamera( 75, w / h, 2, 1000 );
        camera.position.z = 400;

        //Create Scene with geometry, material-> mesh
        scene = new THREE.Scene();
        geometry = new THREE.IcosahedronGeometry( 200, 3 );
        material = new THREE.MeshBasicMaterial( { color: 0x000000, wireframe: true, wireframeLinewidth: 1 } );
        mesh = new THREE.Mesh( geometry, material );
        scene.add( mesh );