Digital Trike’s Guide to JavaScript 3D Animation – Part 2

Last week, we went over the basics of understanding what JavaScript 3D animation is and how it works. This week, we will be showing you how web developers make 3D come to life using HTML code.

As mentioned previously, this blog post is a summary of an article from Smashing Magazine. If you are confused at any time while reading this blog, you may want to refer back to our last week’s blog post!

The Beginning

The first step is to set up an HTML document and canvas as well as include the library.










As you can see, there are two JavaScript libraries that are commented out in the photo above. They are not required but are still worth looking into. Detector.js detects whether WebGL is supported. Stats.js is a JavaScript performance monitor created by the same Mr. Doob who created the Three.js library. Its role is to indicate both frames per second and the time needed to render a frame. Since 3D animations can be extremely taxing on system resources, Stats.js can be very helpful. By monitoring the Stats.js box, you can stay informed in real time on what models or actions are causing low frame rates in your scene.

As we begin to set up the scene, note how much work the API is doing for us; most of our work at the beginning involves no more than setting up the constructors and properties. We will be using the library to set up the scene in the same way that it would be set up in 3D software.

  1. Create the renderer.

  2. Initiate the scene.
  3. Create and position the cameras.

  4. Set up the mesh by combining a new material and new geometry.

  5. Create and position the light source.

  6. Write a function that will render the scene in each frame.

How to add Three.js objects

Before setting up the scene, we need to declare a renderer, set its size, and append it to the window so that we can see what we’re working on.





If you decided to include the Detector.js that was mentioned, you can instead use the following line to check for WebGL support and include a degradation to the canvas renderer if it is not.




Now that the renderer is included, let’s initiate the scene:




Then the camera:






Note that each camera uses a separate constructor. Because we plan to view the scene in three dimensions, we’re using the perspective camera. The first of the properties is the field of view in degrees; so, our view would be at a 45° angle. The aspect ratio is next and is written as width/height. This could obviously be written as 1 here because our scene is going to fit our 600 × 600-pixel canvas. For a 1200 × 800-pixel scene, it would be written as 1200/800 or 12/8; and if you want the aspect to constantly fit the window, you could also writewindow.innerWidth / window.innerHeight. The near and far properties are the third and fourth, giving near and far limits to the area that is rendered.

Placing the camera requires only setting the z-position.




We now need to create a mesh to place in the scene. Three.js eliminates the need to create basic meshes yourself, by including the creation of these in its API by way of combining the geometry and material. The only property we must specify is the radius of the geometry.




While it has defaults, specifying the width and height of the segments is also common. Adding segments will increase the smoothness of the mesh but also decrease performance.




To create a mesh out of this new geometry, we still need to add a material to it. Because we want this rock to really show off the light coming from our perspective camera, we’ll add the shiny phong material. Adding this material is as simple as calling it and setting the color property. Notice that the hex color requires the 0x prefix, indicating that it is a hex value.




In Three.js, the actual mesh is created by combining the geometry and material.To do this, we just have to call the Mesh constructor and add both the geometryand material variables as arguments.




Now that the mesh is declared, we can add it to the scene.




Recalling the introduction, a mesh needs a light source in order to be viewed properly. Let’s create a white light in the same way we initiated the mesh; then we’ll specify exactly where we want the light to be placed and add it to the scene in the same way we added the mesh.




The positions can be written in one of two ways, depending on what you are trying to accomplish.








Render the Scene

We have everything we need for a basic scene, so all that’s left is to tell the renderer to run by creating a render loop. We’ll use requestAnimationFrame() to inform the browser of the upcoming animation, and then start the renderer with the scene we’ve created. Note that requestAnimationFrame() has limited support, so check out Paul Irish’s shim to make sure all of your users get the same experience.






If you open this in your browser, you’ll see the ball in the middle of the canvas with the light reflecting off of it. At this point, play around with the properties to get a better idea of how small changes affect the scene.

Now that the scene is rendered, we can add a simple animation as a starting point. The render loop is already firing every animation frame, so all we have to do is set the speeds, and then we can view the animation right away.









Giving Control to the User

If you’re interested in Three.js for game creation, then you’ll want the user to be able to interact with the models on the screen. Map the commands likesphere.position.x +=1 to character-key codes, which will give the user control (in this case, by using the W, A, S and D keys to move). A simple switch statement will assign the key codes to the position changes. Combining position changes with the opposite rotation change will make the ball appear to roll (for example,position.y += 3 with position.x -= 0.2).












If you want to also include the Stats.js library, then add it to your document using the following:








Going back to the demo, you should have a rock that rolls in the direction of your key press, along with statistics running in the corner if you choose.


This article barely scratches the surface of the Three.js library. Once you are comfortable with the API, experimenting with particles, mapping and more complicated meshes can yield incredible results.

If you want to better understand how to work in 3-D but don’t have access to Maya or 3ds Max, then Blender is available for free. If you would rather stay in the browser, a few sandbox apps were created in Three.js that will work for you. An editor can be found on the Three.js home page. An alternative is actually a featured project on the home page called ThreeFab and is currently in alpha.

Three.js is a gold mine for creating beautiful and complex Web experiments. Taking the extremely simple demonstration explained here and turning it into a mind-blowing experiment merely takes experimentation and the willingness to try new things.

Want to see an example of a 3D object created from Digital Trike? Check this out!