3D graphics tutorial

Drawing objects
My sister's handmade cards on Etsy.
Drawing of a pile of animals

So now we have a representation of our cube, we need to find a way to draw it.

To draw a 3D object on a 2D surface, we need to "project" it. Imagine shining a light behind the cube and projecting it's shadow onto a screen. The simplest form of projection is an orthogonal projection, which is what you would get if the beams of light were parallel to one another.

All this talk of projections might sound complicated, but it is very easy to implement: we just ignore the z-coordinates when drawing.

Setting up

I like to create variables at the top of my programs to control how things are displayed, so I can easily change them later. Here are some variables we will want shortly; feel free to change the values.

var backgroundColour = color(255, 255, 255);
var nodeColour = color(40, 168, 107);
var edgeColour = color(34, 68, 204);
var nodeSize = 8;

Now we add a basic draw function:

var draw = function() {
    background(backgroundColour);
};

We will also need to add the following to our code:

translate(200, 200);

This shifts our canvas 200 pixels left and 200 pixels down, so the pixel at position (0, 0), is now in the centre of our canvas. This means that our cube will be draw in the centre of the screen. The reason for doing things this way will become clear when we start to rotate our objects.

Drawing nodes

Inside the draw function we loop through all the nodes and draw an ellipse at the (x, y) coordinate of that node:

fill(nodeColour);
noStroke();
for (var n = 0; n < nodes.length; n++) {
    var node = nodes[n];
    ellipse(node[0], node[1], nodeSize, nodeSize);
}

Drawing edges

Also inside the draw function we add the code for drawing edges. I would add it before the code for drawing nodes, so the nodes are drawn on top of the edges.

stroke(edgeColour);
for (var e = 0; e < edges.length; e++) {
    var n0 = edges[e][0];
    var n1 = edges[e][1];
    var node0 = nodes[n0];
    var node1 = nodes[n1];
    line(node0[0], node0[1], node1[0], node1[1]);
}

This code loops through the array of edges. It gets the two numbers defined by an edge and looks up the corresponding node in the nodes array. Then it draws a line from the (x, y) coordinate of the first node to the (x, y) coordinate of the second node.

You can see the complete code here.

Is that it?

An underwhelming cube
A cube viewed end on is a boring square.

We set out to draw a cube and all we've done is draw a square and four circles. We could have drawn that with a lot less effort. However, this really is our cube object - it's just that we're viewing it end on. If we can work out how to rotate our cube object so it's no longer end on to the screen, we'll see that it's not just a square and four circles.