To make this happen in code, we'll need to perform 3D vector mathematics.
High-quality JavaScript vector libraries do exist. However, the textbook does not use one. To minimize dependencies, all necessary vector-handling is defined as simply as possible here.
Represent a 3D vector as a 3-element JavaScript array. This approach matches the use of nested arrays for geometry representation. For example:
var a = [1, 0, 0];
var b = [0, 1, 0];
Subscripts translate into JavaScript array references.
a[0]
a[1]
a[2]
Vector addition is then an array of array element additions:
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
Vector subtraction:
[a[0] − b[0], a[1] − b[1], a[2] − b[2]]
The dot product is a scalar value:
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
The cross product:
[
a[1] * b[2] − a[2] * b[1],
a[2] * b[0] − a[0] * b[2],
a[0] * b[1] − a[1] * b[0]
]
To write each of these operations out in full with each use would lead to lengthy and error-prone programs. It's best to translate each of these into a separate JavaScript function.
function add(a, b) {
return [
a[0] + b[0],
a[1] + b[1],
a[2] + b[2]
];
}
Implementations of vector subtraction, dot product, and cross product will be similar.
Additionally, vector normalization is extremely common. Given a JavaScript function for the dot product, a normalize function might look like this:
function normalize(a) {
var len = Math.sqrt(dot(a, a));
return [
a[0] / len,
a[1] / len,
a[2] / len
];
}