<img alt="" src="https://secure.leadforensics.com/150446.png " style="display:none;">
Go to top icon

Three JS – 3D objects on web

Geetanjali Pukale Feb 17, 2015

Java Technology

When the task of rotating a tetrahedron on the web came to me, I was thinking about ways to achieve it. I knew it was possible having seen it on one of our client projects.

I started my research and began my baby steps towards drawing a 3D object and showing it on webpage. I zeroed down on a couple of options but chose - Three JS.

What is Three JS?

It is a wonderful library which provides many functions and guidelines to plot 3D objects and rotate, zoom in & zoom out and various functionalities you can’t imagine. So, it’s perfect for such a need.

But wait! I forgot to tell you the pre-requisites. The basic need is a browser which supports Canvas, WebGL and SVG. Simply, you need a browser which supports HTML 5. All the latest versions of browsers support these new features.

Now let’s take a look at the minimum steps needed to plot a 3D cube on screen.

1) Download three.min.js in say “js” directory. The link : http://threejs.org/build/three.min.js
2) Create a HTML file say cube_rotate.html

<html>
<head>
<title>Cube Rotate</title>
<style> 
body { margin: 0; } canvas { width: 100%; height: 100% } 
</style>

 </head>
<body> <script src="js/three.min.js"></script>
 <script>
 // Our Javascript will go here. 
</script>
 </body>
 </html>

3) Add scene, in this scene add the object. The code is :

var scene = new THREE.Scene();

4) Now add a camera to see the scene. This camera can be of different types. Up till, now I have used perspectiveand orthographic camera. The code:

var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); // parameters: view, aspect ratio, near  clipping plane, far clipping plane

5) Now render the scene and camera. The code would be

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

For older browsers you can have a function which will return rendered based on the browser support. The code is:
function webglAvailable() {
 try {
 var canvas = document.createElement( 'canvas' );
return !!( window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ) );
       } catch ( e ) {
return false;
    }
 	}
		// function call
 if ( webglAvailable() ) {
 renderer = new THREE.WebGLRenderer();
 }
 else {
 renderer = new THREE.CanvasRenderer();
}

6) Now the real cube comes in to the picture. Add a cube to the scene noting the fact that a cube here is just a geometry figure with a set of points which you cannot see unless you have some material associated with it. There is also one concept called ‘Mesh’ which is used to take an object and add material to it. In the next few steps, define the material and then add it to your geometry with help of mesh.

var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );
 camera.position.z = 5; //

(By default, when you call scene.add(), the thing you add will be added to the coordinates (0,0,0). This would cause both the camera and the cube to be inside each other. To avoid this, simply move the camera out a bit.)
7) You may think that everything is good to go. However, you need to write some more code to make it visible on screen i.e. do the actual rendering process.

function render()
 {
 requestAnimationFrame( render );
 renderer.render( scene, camera );
}
 render(); // this is my function call

8) Now animate this cube

cube.rotation.x += 0.1;
 cube.rotation.y += 0.1;

The complete code will be

<html>
	<head>
		<title> Cube Rotate </title>
<style>
			body { margin: 0; }
			canvas { width: 100%; height: 100% }
		</style>

	</head>
	<body>
		<script src="js/three.min.js"></script>
		<script>
			var scene = new THREE.Scene();
			var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

			var renderer = new THREE.WebGLRenderer();
			renderer.setSize( window.innerWidth, window.innerHeight );
			document.body.appendChild( renderer.domElement );

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

			camera.position.z = 5;

			var render = function () {
				requestAnimationFrame( render );

				cube.rotation.x += 0.1;
				cube.rotation.y += 0.1;

				renderer.render(scene, camera);
			};

			render();
		</script>
	</body>
</html>

Here’s how it looks:

VIDEO

In the next blog, we will examine complex examples with mouse interactions.

Keep coding until then :)

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.