Rotation Matrix about arbitrary point

javascript, math

Solution

There are two problems in your code:

The matrix multiplications are done in the opposite order than you probably intend. It looks like you intend `rotate(t, theta)` to return a matrix that applies `t` followed by a rotation, but in fact it's the opposite - the rotation will be applied before `t`. You need to reverse the parameter order in the calls to `matrixMultiply` in `rotate` and `translate`.

The parameters to the CSS `matrix` function are in the wrong order. It should be `a11, a21, a12, a22, a13, a23`. What you are passing in is `a11, a12, a21, a22, a13, a23`.

Here's the fixed version.

Problem

By default, the rotation matrix uses the origin point as the center of the rotation. To rotate around an arbitrary point, you have to subtract the distance to the origin using a translation matrix, do the rotation, and then translate back. Except that this doesn't seem to work so well for me. I have the following code (assume my object is 100x100 with a center at 50,50): ``` t = IDENTITY; t = translate(t, -50, -50); t = rotate(t, theta); t = translate(t, 50, 50); ``` Unfortunately, if I apply this transform matrix `t` to my object, the object is positioned incorrectly. I've implemented a quick jsfiddle to demonstrate my problem: http://jsfiddle.net/9M3uy/67/ In the JSFiddle, the red rotated square is where the rotation should have ended up (courtesy of CSS3's built in transform-origin), and the blue rotated square is where my computation ends up (the green would have been the original non-rotated square). Any ideas? Am I just not understanding how the translate,rotate,translate back mechanic works or am I doing something horribly wrong?

Original source