3D-Visualization and gaming has come a long way since just two decades ago, when implementations required a lot of overwork, including third-party plug-ins, and in some cases also required capturing of motion graphics for commercial 3D gaming.
The possibilities are endless–from simulating an actual fluttering cloth to a simulation of an entire universe with plants to implementing a 360-degree view of a room. The rendering of landscapes and terrains are nearly perfect examples of the beauty of these frameworks. Below are a few examples of what can be achieved with these frameworks:
As a brief introduction, let us take a look at the interiors of Three.js. For any 3D visualization, we would require the following objects:
To begin, we would implement an animated cube. The declaration of objects that we would need comes first:
var camera, scene, renderer; var geometry, material, mesh;
We require two functions–init() and animate().
The init() function creates and sets the position of the camera, creates a cubic geometrical shape, defines the material of the mesh that the shape would be composed of, adds the shape and the mesh onto the scene, and renders the entire scene on a canvas element.
The code for the entire init() function is listed below:
There are multiple types of camera classes provided by Three.js, out of which THREE.PerspectiveCamera is used for a perspective view of the scene. The scene can be added with a mesh (where mesh is composed of a geometrical shape and the colour, or texture, or image that defines how the shape would look), which is implemented by using the THREE.MeshBasicMaterial class. Again, Three.js provides a vast collection of classes of material that can be applied to different geometrical shapes.
The most important aspect is the rendering of the objects that makes WebGL with Three.js or Babylon.js easy to work with. Three.js provides a class THREE.CanvasRenderer that renders the objects automatically on the HTML5 canvas element. This provides a very graceful fallback in case WebGL (which is dependent on the compatibility of the latest browsers) is not compatible with the browser being used at client end.
The animate() function makes use of the requestAnimationFrame() function to perform a call back of the animate() function itself, which updates the animation before the next repaint takes place in the browser. For this example, the rotation vector is updated for the mesh in the scene in any subsequent repaints. The code for the animate() function is listed below:
The animating Cube example can be viewed on the demo link.