An Introduction To Three JS
Posted By : Rajan Rawat | 08-Jun-2018
Three js
3D graphics is very difficult to create and it becomes so difficult when it comes to
In this article, we are going to create a scene with a spinning cube and it is shown in below example
First step
As our first set to save
Create the scene
As the general knowledge for creating we need some things like a scene, renderer, and camera. So we create or renderer a scene with help of camera
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 );
now let me explain all this here we are using a PerspectiveCamera.
So our first attribute is FOV(field of view) and its value is in degrees.
The second attribute is the aspect of ratio. This attribute will maintain the balance between and height and width of scene and screen that we are going to use.
The next attribute is going to use near and far clipping plane. This means the object is away from the camera than the value of far and closer than the near will not be rendered. so you don't have to worry about these things further
Now the last thing is we will add the renderer element in our HTML file. This is canvas element uses to display the scene of a renderer
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;
The Final Code
So now this is a complete code given below which makes a 3D graphics for you.
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 animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render( scene, camera );
};
animate();
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rajan Rawat
Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.