# super simple 3d rendering

I always thought 3d projection was really hard. But this wikipedia article shows that you only need basic linear algebra! For every 3d point you just have to do two transformations. The camera transform:

$$\begin{bmatrix} \mathbf{d}_x \\ \mathbf{d}_y \\ \mathbf{d}_z \end{bmatrix}=\begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos ( \mathbf{\theta}_x ) & \sin ( \mathbf{ \theta}_x ) \\ 0 & - \sin ( \mathbf{ \theta}_x ) & \cos ( \mathbf{ \theta}_x ) \end{bmatrix}\begin{bmatrix} \cos ( \mathbf{\theta}_y ) & 0 & - \sin ( \mathbf{ \theta}_y ) \\ 0 & 1 & 0 \\ \sin ( \mathbf{\theta}_y ) & 0 & \cos ( \mathbf{\theta}_y ) \end{bmatrix}\begin{bmatrix} \cos ( \mathbf{\theta}_z ) & \sin ( \mathbf{\theta}_z ) & 0 \\ -\sin ( \mathbf{\theta}_z ) & \cos ( \mathbf{\theta}_z ) & 0 \\ 0 & 0 & 1 \end{bmatrix}\left( {\begin{bmatrix} \mathbf{a}_x \\ \mathbf{a}_y \\ \mathbf{a}_z \\ \end{bmatrix} - \begin{bmatrix} \mathbf{c}_x \\ \mathbf{c}_y \\ \mathbf{c}_z \\ \end{bmatrix}} \right)$$

where c is the camera position and a is the 3d point you want to project onto the screen. And then you have to do the perspective transform:

\begin{align} \mathbf{b}_x &= \frac{\text{screen width}}{2} + \frac{\mathbf{d}_x}{\mathbf{d}_z} f \\ \mathbf{b}_y &= \frac{\text{screen height}}{2} - \frac{\mathbf{d}_y}{\mathbf{d}_z} f \end{align}

where f is the field of view factor. Then bx and by are the respective x and y coordinates on the screen.

Given these transforms I made a simple 3d line renderer in javascript using the 2d line draw function provided by the canvas. You can click and drag to move the camera, and use the arrow keys to move the cube. For the simple physics simulation I used the verlet integration method.

The javascript code can be found in the source code of this page.