Lavonen
Lavonen

Reputation: 670

Putting three.js inside of div 2

I apologize for one more basic question which basically is a copy of another old thread, but I'm new to three.js and learning more or less through trial and error over here...

I found the old thread 'Putting three.js animation inside of div' where they succeeded putting a three.js animation inside of a div with the following lines of code:

container = document.getElementById( 'canvas' );
document.body.appendChild( container );
renderer = new THREE.WebGLRenderer();
renderer.setSize( 200, 200 );
container.appendChild( renderer.domElement );

A JSFiddle of above script (http://jsfiddle.net/fek9ddg5/1/)

I'm trying to do the same and added the lines to my script, but ended up with a completely white screen instead. I managed to basically part the screen in two parts, one completely white and another with the script. However, it failed since the script reacted to the mouse even if it moved in the white part. I made a codepen, I placed the script I added inside of comment-signs.

See it here: http://codepen.io/anon/pen/qRdGWo

Upvotes: 1

Views: 2565

Answers (1)

2pha
2pha

Reputation: 10165

Usually to add three.js to a page I would use this:

renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
// Add renderer to page
document.body.appendChild(renderer.domElement);

// Create camera.
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 400;

As can be seen in this fiddle

But, to add it to a div that is already on the page with the ID 'canvas-container' I would use..

renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
// get the div that will hold the renderer
var container = document.getElementById('canvas-container');
var w = container.offsetWidth;
var h = container.offsetHeight;
renderer.setSize(w, h);
// add the renderer to the div
container.appendChild(renderer.domElement);

// Create camera.
camera = new THREE.PerspectiveCamera(70, w / h, 1, 1000);
camera.position.z = 400;

Which can be seen in this fiddle

Basically where the renderer is added is determined on what dom element you call appendChild(renderer.domElement) on.

Upvotes: 5

Related Questions