3D graphics tutorial

Creating objects
My sister's handmade cards on Etsy. I think the simplest shape to start working with is a cube. Although a tetrahedron has fewer sides, its sides aren't orthogonal, which makes things trickier. Let's start by creating a 200×200×200 pixel cube, centred at the origin (0, 0, 0).

Nodes

Your browser doesn't support canvas.

The nodes of a 2x2x2 cube, centred on the origin.

We start by defining an array of nodes, where each node is an array of three digits, the x, y and z coordinates of that node:

var node0 = [-100, -100, -100];
var node1 = [-100, -100,  100];
var node2 = [-100,  100, -100];
var node3 = [-100,  100,  100];
var node4 = [ 100, -100, -100];
var node5 = [ 100, -100,  100];
var node6 = [ 100,  100, -100];
var node7 = [ 100,  100,  100];
var nodes = [node0, node1, node2, node3, node4, node5, node6, node7];

Notice that the nodes are all 8 ways of arranging three lots of positive or negative 100.

Edges

Your browser doesn't support canvas.

To define edges, you need to know the index of each node.

Next we define an array of edges, where each edge is an array of two numbers. For example, edge0 defines an edges between node0 and node1. We start counting at 0 because arrays are indexed starting at zero (To get the value of the first node we type nodes).

var edge0  = [0, 1];
var edge1  = [1, 3];
var edge2  = [3, 2];
var edge3  = [2, 0];
var edge4  = [4, 5];
var edge5  = [5, 7];
var edge6  = [7, 6];
var edge7  = [6, 4];
var edge8  = [0, 4];
var edge9  = [1, 5];
var edge10 = [2, 6];
var edge11 = [3, 7];
var edges  = [edge0, edge1, edge2, edge3, edge4, edge5, edge6, edge7, edge8, edge9, edge10, edge11];

The tricky part is making sure you join the right edges together. I find it helps to draw a diagram. Mouseover the edges in the code above to highlight the edge in the diagram.