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?
Rotation about an arbitrary point: If we want to rotate an object or point about an arbitrary point, first of all, we translate the point about which we want to rotate to the origin. Then rotate point or object about the origin, and at the end, we again translate it to the original place.
To perform the rotation on a plane point with standard coordinates v = (x, y), it should be written as a column vector, and multiplied by the matrix R: If x and y are the endpoint coordinates of a vector, where x is cosine and y is sine, then the above equations become the trigonometric summation angle formulae.
Rotations are matrices. We know what the rotation function Rα : R2 → R2 does to vectors written. in polar coordinates. The formula is. Rα(r( cos(θ),sin(θ))) = r( cos(θ + α),sin(θ + α))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With