3D in D3

I have spent some time lately with D3. It's a lot of fun to build interactive graphs. See for instance this demo (will provide a longer writeup soon).

D3 doesn't have support for 3D but you can do projections into 2D pretty easily. It's just old school computer graphics. I ended up adding an animated background to this blog based on an experiment. The math is simple.

First, there's the rotation. Given a bunch of 3D coordinates, how do you rotate them in 3D space? The cleanest way is to define angles $$ \alpha, \beta, \gamma $$ and use them for rotation in the yz-plane, xz-plane, and xy-plane, respectively. Each of them define a rotation matrix. For the xy-plane, we get the rotation matrix $$ R_{xy} $$ (see code):

$$ R_{xy} = \begin{pmatrix} \cos(\gamma) & -\sin(\gamma) & 0 \ \sin(\gamma) & \cos(\gamma) & 0 \ 0 & 0 & 1 \end{pmatrix} $$

We get three of these matrices in total: $$ R_{yz}, R_{xz}, R_{xy} $$ .

The rotation of any vector $$ \mathbf{v} $$ can now be described as $$ R_{yz} R_{xz} R_{xy}\mathbf{v} $$ . The nice thing is we can _precompute_ the product of these matrices $$ R $$ (see code). Math porn:

$$ R = \begin{pmatrix} 1 & 0 & 0 \ 0 & \cos(\alpha) & -\sin(\alpha) \ 0 & \sin(\alpha) & \cos(\alpha) \end{pmatrix} \begin{pmatrix} \cos(\beta) & 0 & \sin(\beta) \ 0 & 1 & 0 \ -\sin(\beta) & 0 & \cos(\beta) \end{pmatrix} \begin{pmatrix} \cos(\gamma) & -\sin(\gamma) & 0 \ \sin(\gamma) & \cos(\gamma) & 0 \ 0 & 0 & 1 \end{pmatrix} $$

 

Now going forward we can use the matrix $$ R $$ to rotate any vector $$ \mathbf{v} $$ (see code).

The other thing you want to do is to make distant objects look further away. Thinking through proportionalities you can derive a pretty simple equation (see code). $$ x� = x / (z/d + 1) $$ , and same for $$ y $$ . The constant $$ d $$ is just a hack to scale down the $$ z $$ values.

Not sure whether the 3D animation is cool or just annoying, but I'll prob keep it for a bit – enjoy!

Tagged with: misc, math