Tuesday, 14th June 2011
Rotating 3D SVG Cube
Since getting my head around how 3D graphics work (to a degree at least), I thought I'd apply what I know to my favourite format: SVG. Below is an SVG displaying a sqaure, but if you click on the arrows, the shape changes, giving the appearance of a cube rotating about either the x- or y-axis.
The SVG works by storing the x-, y- and z-coordinates of a cube in three separate arrays. When the arrows are pressed, these values are transformed, and the x and y positions of the twelve lines that make up the edges of the cube are updated. The code for the transformation is almost identical to that in my Python program -- there is even a Math.atan2() function. To see the code in more detail, either right click on the SVG and choose View Frame Source, or click on the link at the bottom of this post.
Another feature of this SVG which I'm pleased about is the fact that the functions are repeated called if the mouse is held down on the buttons. I've described how to do this here.
I made this SVG pretty quickly and I think it's pretty inefficient. There's quite a lot more I could do if I get some time:
- Use matrix transformations. I'm not sure if ECMAScript can multiply matrices natively, but it should be easy enough to write a function for it. This should make the code a bit more efficient and save having separate functions for rotating about the different axes.
- Make a more complex shape. I already have a Python .obj reader and it should be quite easy to make this output SVG files. Then I could view more complex shapes created in other programs.
- Shade the surfaces. I have a Python program that does this reasonably well, so I could try to adapt the code for this. It would be interesting to see how fast the program can run.
- Add more transformations. I could add rotation about the z-axis, zooming and translations. I could try to make an entire 3D game, but I think that would be going too far.