JavaScript Ray-Tracing: or The Worst Application of JavaScript Ever

Results of the JavaScript ray tracerLet me preface this post with the statement that this experiment has probably been a complete waste of time, nobody will ever need a JavaScript based ray-tracer. The point of the exercise was actually to learn more about the Canvas HTML element, and ray tracing techniques, not JavaScript.

I picked up a particular fondness for ray-tracing during my University years while studying Computer Science, majoring in Computer Graphics. Ray Tracing is quite a simple idea which produces quite impressive results with relatively little work.

One of the first things I like to do with a language is crack out a simple ray tracer. It’s a good test of the language (as I understand it), as well as the computing power of the system it’s running on, and I suppose in this case, it’s a good test of the browser’s JavaScript engine.

Ray-tracing is a very intensive algorithm. Abstracting the maths away a bit, it basically casts a ray (yep, hence “ray tracing”) over the scene (a collection of shapes and lights all represented in 3D space) for every pixel of the image, bouncing the ray around the scene multiple times as it hits objects (this is how reflections work, etc).

Most good ray-tracers use a number of optimisation techniques in order to speed up these expensive operations. For instance, integer bit shifting is a common source of speed-boosts. JavaScript’s everything-is-a-float is obviously not going to provide anywhere near good performance.

The Canvas

As I said, the main point of this exercise was to learn more about the Canvas element. If you want to learn more about Ray Tracing, there are a number of great resources on the the net.

The canvas element has a pretty simple API: simply get the 2D context and render to it. I was thinking of documenting my usage of it, but it’s already done so well on other sites that I figure I’ll just link you off to them to learn more.

The Flog.RayTracer in action

Click here to open the no-frills ray-tracer interface in a new window

If you’re really keen feel free to go ahead and download the ray-tracer. It’s probably very buggy (I know of a couple of big ones already), but it’ll give you hours of fun trying to fix it.


About this entry