7
votes

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?

2
You must be using Chrome or Safari. I updated the JSFiddle to include the necessary CSS for all browsers.syazdani
Yes! But it seems you found the answer! I came too lateAnder Biguri

2 Answers

2
votes

There are two problems in your code:

  1. 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.

  2. 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.

0
votes

Try to implement first the "standard" 3x3 matrix multiplication for 2d -cases and only after try to optimize away the elements, which result from multiplying by zero. It a bit hard to see if the formulas are correct, when the indexing scheme is far too unorthodox.

The rotation matrix = [c -s 0; s c 0; 0 0 1]; The translation matrix = [1 0 x; 0 1 y; 0 0 1];

I have to assume css -translation function also assumes 3x3 result.

Both multiplication and rotation is performed by multiplying vectors (x,y,1) by the corresponding matrix.

EDIT: After fiddling a bit, it appears that either the matrix m should be translated, or the operators could be defined as return MatMul([rot matrix],m) and return MatMul([trans matrix],m)

EDIT2: Now I can see something strange: translating only by +-50, +-50 and rotating by ~10 degrees, the corner doesn't stay in the middle of the red square. But don't understand the format of css matrix anyway. Sorry...