3D rotating object using HTML5 and JavaScript

This is my first attempt at coding 3D graphics so it’s pretty raw. All rendering is done in JavaScript by calculating the object’s coordinates and then drawing lines directly onto a HTML5 Canvas object.

The maths is almost entirely matrix and vector manipulation. The main calculations are: rotating an object in 3D, calculating a vector perpendicular to a plane, and working out if the perpendicular vector and the “camera” vector are pointing towards each other (and if so, render the plane).

3D Rotating Object

What this code does: it handles the 3D rotation, distance and perspective of an object and works out what planes of the object are visible and need to be rendered. It also optimises the rendering, so a line that borders two visible planes will only be drawn once. The rotation of the object is constant across all devices, but the framerate is the maximum the browser can support. This allows the object to rotate as smoothly as the local hardware and browser will allow.

What this code doesn’t do: you’ll notice the object is convex, which means no part of the object can ever obscure another part. This is due to a limitation in the code as there is currently no facility for one part of an object to intelligently obscure another part. Also, the code does not allow a near object to obscure a distant object – at the moment both will be rendered. I’m going to fix these issues next.

If you have a JavaScript enabled HTML5 browser, you can view the working code here.