Update: Newer WebGL based version

This is an old experiment. I created a newer much faster webgl powered library for you to play with this technique. It's called normalmap.js. It allows you to easily apply normal mapping for interactive lighting effects in javascript.

Original Article

I made a little experiment with normal mapping and phong shading in javascript which turned out to work quite well. I think with a little bit of tweaking it could be used in a real time game. Just move your mouse over the images bellow to see it in action. You'll need a modern browser supporting the canvas tag for this to work. Google Chrome seems to be the fastest.

Demo

Source

You can view the source code here: light.js. Feel free to copy from it, but please notify me if you use it for something cool. :) Also beware that the code is pretty hacky and unpolished.

How it works

The 3D effect is basically created using 2 textures. One contains the color of each pixel and the other the surface normal. The color image is rendered using only indirect lighting (ambient occlusion in that case). The direct light is then calculated in real time using phong shading without the diffuse part. For a more accurate description, read the source. ;)

Credits

The dragon head used in this demo comes from planetpixelemporium.com. The Buddah is from the Stanford 3D Scanning Repository and was rendered and baked using blender. Thanks for letting me use it.