Creating a context and rendering a mesh in THREE.js

What follows is slightly modified from the introduction to creating scenes on the Three.js website itself.

Three.js is a popular framework for making 3D graphics for the Web. We include it in our html document with a <script> tag:

		<script type="text/javascript" src="js/three.js"></script>
		

We initialize a WebGL context by creating a new WebGLRenderer, setting its width and height, and adding it to the html document.

		var renderer = new THREE.WebGLRenderer()
		renderer.setSize( 320, 240 );
		document.body.appendChild( renderer.domElement );
		

We now have an empty context. We’ll also need a scene and a camera.

		var scene = new THREE.Scene();
		var camera = new THREE.PerspectiveCamera(75, 320 / 240, .1, 100)
		camera.position.z = 5;
		

Let’s create an object and add it to the scene.

		var geometry = new THREE.BoxGeometry( 1, 1, 1 );
		var material = new THREE.MeshBasicMaterial( { color: 0xff00ff } );
		var cube = new THREE.Mesh( geometry, material );
		scene.add( cube );
		

We can define an update() function that will rotate our cube every time it is called:

		function update(){
			cube.rotation.x += 0.01;
			cube.rotation.y += 0.01;
		}
		

And a render() function that calls update(), renders scene, and also calls itself again and again in an endless loop (that recursion is controlled by the requestAnimationFrame part at the beginning). Note also that the renderer needs to know about the scene and the camera.

		function render() {
			requestAnimationFrame( render );
			update();	
			renderer.render( scene, camera );
		}
		

Finally, we call render()

	render();