Wednesday, November 1, 2017

Working with the three.js Library to create 3D objects using JavaScript


I've had a growing curiosity recently in what code makes the Magic of Pixar films happen. They must be using some software to create the beautiful images and characters we all know and love. But who makes sure that software is functioning properly? What Magic is happening behind the scenes? 

After a little digging, I found that they mostly program their software in C or C++, so I'm not quite there yet, but I did find a JavaScript library that offers the ability to create 3D models and objects. So I'm going to dive into the basics of that.


The three.js library was created in 2010 by Ricardo Cabello. It was made with the intention of displaying 3D images in the web browser without a plug-in or standalone application.
It is built on top of the WebGL (Web Graphics Library) API, made for rendering 2D and 3D graphics. three.js is to WebGL similar to what JQuery is to Javascript, syntactic sugar allowing many of the same actions to be performed with less code.
The documentation on three.js is very good and detailed. They walk you through creating your first 3D object line by line. 



The first step was to create a project and saving the three.js files to the directory. Then I created an index.html file and required <script src="three.js/build/three.js"></script>.

Next, within the script tags I included the following code: 

In order to create an animated 3D object, three things are required: A scene, a camera, and a renderer. The Scene is like the environment in which the object is created. The camera is the perspective from which the viewer sees the object and the renderer... well, renders the object to the page.

The scene is a container that defines what will be rendered and where it will be placed.

The camera takes arguments, a field of view, an aspect ratio, and the last two define the boundaries within which the object will be rendered. if the camera is too near the object or far away, it won't render.

The renderer is where things get good! This is where the element is added to the DOM and defined. You set the size, shape, and color of the object using built-in methods. Here you also need to use a mesh to dictate the material that will be applied to the shape that can then be colored, making it visible and movable.

Finally, an animation function is added to make the object appear on the page and move.



Then, I was able to add custom javascript to randomly change the colors on reload. I also adjusted the speed of the animation and shape of the object.




For the following animation, I changed the geometry type to a cone. 



There are many other geometry options including rings, spheres, planes and even text. It's also possible to add lighting effects to the object so that objects like spheres will have dimension and not appear as a flat circle. 



Any Questions?

No comments:

Post a Comment