HTML and CSS Reference
In-Depth Information
This function is hard-coded to multiply a 1 × 3 matrix by a 3 × 3 matrix, because that's what we need it to
do. You can make a more dynamic function that can handle any sized matrices using iteration techniques,
but let's keep things simple here.
Finally, create the rotateY function, which, if you understand the rotateX function, should look similar.
You just create a y rotation matrix instead of an x rotation matrix.
function rotateY (ball, angle) {
var position = [ball.xpos, ball.ypos, ball.zpos],
sin = Math.sin(angle),
cos = Math.cos(angle),
yRotMatrix = [];
yRotMatrix[0] = [ cos, 0, sin];
yRotMatrix[1] = [ 0, 1, 0];
yRotMatrix[2] = [-sin, 0, cos];
var result = matrixMultiply(position, yRotMatrix);
ball.xpos = result[0];
ball.ypos = result[1];
ball.zpos = result[2];
}
Save the updated example as 01-rotate-xy.html and run it in your browser. Compare the output of this
to the version from Chapter 15 and they should look exactly the same. If you want, you can also create a
rotateZ function, but because we don't actually need that for this example, that's left as an exercise for
you to do on your own.
Even if you don't use matrices for 3D, you'll still find them useful for other purposes. We cover these next.
Their use here provides a nice introduction because you can see how they relate to formulas you already
know. Also, because matrices are used extensively in other graphics environments, if your programming
life takes you elsewhere, you'll be ready!
Canvas transforms
One poweful feature of matricies is that they can be used to manipulate the canvas display. By applying a
transformation, we can rotate, scale, and translate how the shapes are drawn, altering their form, size, and
position. The canvas context uses a 3 × 3 transformation matrix set up like so:
a c dx
b d dy
u v w
This setup is known as an affine transformation , which means we are representing a 2-vector (x, y) as a 3-
vector (x, y, 1). Because we won't use u , v , w , the extra space is filled in with 0, except for the lower-right
corner that is set to 1. These remain unchanged, so you don't have to worry about them.
You can set the transformation of the canvas context by calling:
context.setTransform(a, b, c, d, dx, dy);
 
Search WWH ::




Custom Search