Back

In my last post I wrote about how to draw a pretty awesome square - this time, we'll add an extra dimension. Hopefully I'll be able to demonstrate that it's not nearly as complicated as it sounds, most of the discussion will follow from the first post so make sure you've read that first.

First, let's define our cube. A cube has eight points (corners) and six faces. Again, we'll define our object relative to the origin `[0, 0, 0]`, and we'll position the corners at `[1, 1, 1]`, `[-1, 1, 1]`, etc.

``````var cube_faces = [
// front and back
[[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]],
[[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1]],

// left and right
[[-1, -1, 1], [-1, -1, -1], [-1, 1, -1], [-1, 1, 1]],
[[1, -1, 1], [1, -1, -1], [1, 1, -1], [1, 1, 1]],

// top and bottom
[[-1, 1, 1], [1, 1, 1], [1, 1, -1], [-1, 1, -1]],
[[-1, -1, 1], [1, -1, 1], [1, -1, -1], [-1, -1, -1]],
];``````

Note that we'll use the convention that for a vector `[x, y, z]`, `+x` is up, `+y` is right, and `+z` is in to the screen.

We'll start by making a `drawFace` function. This will take an array of 3D world coordinates of our face, project them into an array of 2D screen coordinates, and draw them on the canvas.

Projection is any method of converting our 3D point data into 2D data (that we can draw on our 2D screen). We're going to use a simple perspective projection, which you can read about here. Ever wondered how games deal with changing FOVs or stereographic images? Projection!

So, let's skim over this wikipedia article and extract the formulas we'll need. Following the article let's assume an unrotated camera positioned at `c`, a viewer positioned at `e`, and our 3D point at `a`. We aim to find `b`, the 2D projection onto our canvas. Since our camera is unrotated, we have `d = a - c` and combined with the two equations for `b` we get

``````d = a - c
d = a - c
d = a - c

b = e * (d / d) - e
b = e * (d / d) - e``````

For simplicity, we'll set `c = [0, 0, 0]`. This simplifies our formula even more since now `d = a`.

``````b = e * (a / a) - e
b = e * (a / a) - e``````

Our `drawFace` function should end up looking something like this

``````function drawFace(face_coords) {
var screen_coords = [];

for (var j = 0; j < face_coords.length; j++) {
screen_coords[j] = [
(e * (face_coords[j]) / face_coords[j]) + e,
(e * (face_coords[j]) / face_coords[j]) + e
];
}

// A bit of transparency here means we'll be able to see through our cube.
ctx.strokeStyle = 'black';
ctx.fillStyle = 'rgba(100, 100, 100, 0.4)';

ctx.beginPath();
ctx.moveTo(screen_coords, screen_coords);
ctx.lineTo(screen_coords, screen_coords);
ctx.lineTo(screen_coords, screen_coords);
ctx.lineTo(screen_coords, screen_coords);
ctx.lineTo(screen_coords, screen_coords);
ctx.stroke();
ctx.fill();
}``````

But what about our value for `e`? For now, we'll just set it to `[canvas.width / 2, canvas.height / 2, -200]`. Once everything is running, you can tweak this value to get an understand of what it does.

We need a basic `draw` function to draw all six faces of our cube.

``````function draw(faces) {
var world_faces = faces.map(function(face) {
var world_face = face.map(function(point) {
var world_point = [
(10 * point),
(-10 * point),
(10 * point) - 60
];

return world_point;
});

return world_face;
});

world_faces.map(drawFace);
}

ctx.fillStyle = 'rgb(135, 206, 250)';
ctx.fillRect(0, 0, canvas.width, canvas.height);

draw(cube_faces);``````

Great! Let's try it out. You'll notice that I put a few simple transformations in here. The cube is scaled up by a factor of `10`, the `y` component is inverted (so `+y` is right), and the `z` component is reduced by `60`. This means the cube is move backwards (into the screen) away from the camera.

You should get something like this:

Notice that the rear face is smaller than front face, and the side faces appear to get smaller. Perspective!

Before we get into rotation, there's one more problem we need to solve. Go ahead and set the `fillStyle` for our faces to a solid colour. You'll see something like this.

Since we're looking at the front of our cube we should only be able to see the front face - why can we see edges of other faces?! This happens because the faces are drawn in the order they appear in our `cube_faces` array. That means the cube faces will always been drawn in the order front, back, left, right, top, then bottom. Really, we want the faces that are furthest away from the camera to be drawn first, so subsequent (closer) faces are drawn on top. We can do this by sorting the faces based on their distance to the camera. We'll so this with `Array.prototype.sort`.

``````world_faces.sort(function(a, b) {
var a_center = [
(a + a + a + a) / 4,
(a + a + a + a) / 4,
(a + a + a + a) / 4
];

var b_center = [
(b + b + b + b) / 4,
(b + b + b + b) / 4,
(b + b + b + b) / 4
];

var a_mag = (
a_center * a_center +
a_center * a_center +
a_center * a_center
);

var b_mag = (
b_center * b_center +
b_center * b_center +
b_center * b_center
);

return b_mag - a_mag;
});``````

Given two faces we find the average each faces four corners. This gives us the centre of each face, which we use to compute it's magnitude - this is the distance between the face and the camera (since our camera is at `[0, 0, 0]`). We use the comparision between these two magnitudes to sort `world_faces`. This is called the Painter's Algorithm given that it's similar to how a painter would paint a scene - distant objects first.

Finally, let's beef up our transformations a little. We've got scale and translation, but what about rotation? Another trip to Wikipedia gives us some basic matrices for rotations about the `x`, `y`, and `z` axes. Expanding these matrices out into equations is left as an exercise for the reader... I ended up with something like this:

``````// Rotate X
var tempY = world_point;
var tempZ = world_point;
world_point = tempY * Math.cos(rot) + tempZ * Math.sin(rot);
world_point = tempZ * Math.cos(rot) - tempY * Math.sin(rot);

// Rotate Y
var tempX = world_point;
tempZ = world_point;
world_point = tempX * Math.cos(rot) + tempZ * Math.sin(rot);
world_point = tempZ * Math.cos(rot) - tempX * Math.sin(rot);

// Rotate Z
tempX = world_point;
tempY = world_point;
world_point = tempX * Math.cos(rot) + tempY * Math.sin(rot);
world_point = tempY * Math.cos(rot) - tempX * Math.sin(rot);``````

And a `draw` function that looked a little more like this

``````function draw(faces, scale, rot, trans) {
var world_faces = faces.map(function(face) {
var world_face = face.map(function(point) {
var world_point = [
point,
-point,
point
];

// Rotate X
var tempY = world_point;
var tempZ = world_point;
world_point = tempY * Math.cos(rot) + tempZ * Math.sin(rot);
world_point = tempZ * Math.cos(rot) - tempY * Math.sin(rot);

// Rotate Y
var tempX = world_point;
tempZ = world_point;
world_point = tempX * Math.cos(rot) + tempZ * Math.sin(rot);
world_point = tempZ * Math.cos(rot) - tempX * Math.sin(rot);

// Rotate Z
tempX = world_point;
tempY = world_point;
world_point = tempX * Math.cos(rot) + tempY * Math.sin(rot);
world_point = tempY * Math.cos(rot) - tempX * Math.sin(rot);

// Scale
world_point *= scale;
world_point *= scale;
world_point *= scale;

// Translate
world_point += trans;
world_point += trans;
world_point += trans;

return world_point;
});

return world_face;
});

world_faces.sort(function(a, b) {
var a_center = [
(a + a + a + a) / 4,
(a + a + a + a) / 4,
(a + a + a + a) / 4
];

var b_center = [
(b + b + b + b) / 4,
(b + b + b + b) / 4,
(b + b + b + b) / 4
];

var a_mag = (
a_center * a_center +
a_center * a_center +
a_center * a_center
);

var b_mag = (
b_center * b_center +
b_center * b_center +
b_center * b_center
);

return b_mag - a_mag;
});

world_faces.map(drawFace);
}``````

Remember that order is important. Here I'm rotating around `x`, then `y`, then `z`. With three rotations happening one after the other this can lead to some funky results, but we'll gloss over that for now...

Stitching this all together with a bit of animation

``````var t = 0;

function frame() {
ctx.fillStyle = 'rgb(135, 206, 250)';
ctx.fillRect(0, 0, canvas.width, canvas.height);

draw(cube_faces, 10, [t, 0.6, 0], [0, 0, -60]);

t += 0.01;

window.requestAnimationFrame(frame);
}

frame();``````

And you'll have something like this!

Pretty cool really.