As part of our ongoing programming R&D at Skookum Digital Works, we’ve recently been experimenting with WebGL. If you’re new to the technology and 3d in general, it can be quite a daunting task to get up to speed. Here’s a quick WebGL primer (along with Three.js) to get you started.
As you can see by the above chart, all of the “cool” browsers are WebGL ready. (Safari does require support enabled via the command line). Then of course we have IE. Sadly the folks at Redmond decided not to include the tech in their latest browser. Hopefully things will change with IE 10.
Not for the Faint of Heart
A drawback (of sorts) is that WebGL is basically a wrapper for openGL. The good part about this is that the possibilities are endless. The bad part is that if you are not familiar with 3d/game development then the learning curve is quite high. Here is a brief run-down on the process for creating a cube in straight WebGL:
- Get canvas element with webgl context
- Set viewport
- Configure depth buffer
- Create perspective matrix
- Create modelview matrix
- Create and compile shader(s) and shader program(s)
- Create vertex array
- Create and bind vertex buffer…
View the source on the following demo to see what I mean.
All that for a white box? Yep. Believe it or not that “box” is actually an unlit cube in 3d space, and as you can see it is no trivial task setting things up to render it.
Theres got to be an easier way! Well there is, the answer is Three.js. This WebGL 3D engine from mrdoob is EPICALLY AWESOME! In a nutshell it allows you to easily render 3d scenes with a minimal amount of code, allowing you to focus on the fun stuff. Look at it like jQuery for WebGL.
Check out how much shorter our code is recreating that first demo with three.js
Much easier! We simply:
- Create a scene object
- Create a camera object
- Add models/primitives to the scene
- Add light(s) to the scene
The Fun Stuff
Ok enough with the boring boxes. Here is a demo where we dynamically add spheres to the scene, and then rotate that scene based on the coordinates of our mouse.
As you can see the code is not much longer, and plays nice with others libs like jQuery and sugar. Remember to animate using the requestAnimationFrame instead of setInterval for maximum efficiency.
The Grand Finale
Now if you are still craving more (I know you are). Just take a look at this last demo. It is a modified version of the great app from airtight.cc called the Rutt-Etra-Izer. I have tweaked it to allow the selection of a Skookum’s twitter account. Once the account is selected it will pull in that person’s main profile picture and perform the effect. The z-depth of the lines is determined by the lightness or darkness of the pixel. And you can see the rendering speed of Three.js/WebGL by adjusting the parameters in real time at the left. Have fun!