Confine scene dimensions to container

Hi, I been studying beginner tutorial on three.js but nobody explains how to set the dimensions of the scene to an html element “container” with width 100px, height 200px (for example). All tutorials just automatically set the scene to the max height and width of the window. Can I get some help here? Thank you!

so maybe :slightly_smiling_face:

<!DOCTYPE html>
<head>
	<title> test2 </title>
	<meta charset="utf-8" />
</head>
<body> 	
<div id="container"  width="200" height="100" ></div>
 
</body>
	<script src="js/three.min.100.js"></script>
	
<script>

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 55, 200 / 100, 0.1, 1000 ); //width="200" height="100" 
camera.position.set( 0, 1, 4 );
var renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( 200, 100 ); //width="200" height="100" 
renderer.setClearColor( 0xdddddd, 1 );	
var container = document.getElementById( "container" );
document.body.appendChild( container );
container.appendChild( renderer.domElement ); 


var geometry = new THREE.BoxBufferGeometry( );
var mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial( { color: 0xff00ff } ) );
scene.add( mesh );

animate();

function animate() {

	requestAnimationFrame( animate );	
	renderer.render( scene, camera );
	
}
</script>

</html>
2 Likes

I would recommend this approach. First add a reference to your container element:

var myContainerElement = document.getElementById( “container” );

Then later on when you set the renderer’s size, use this instead:

renderer.setSize( myContainerElement.width , myContainerElement.height );

If you are using a resize event listener, then make sure to put there the line above as well. This way the renderer size will dynamically adapt to your containers dimensions.

3 Likes