Reputation: 2014
Im trying to figure out how to "center point" the big red square on the blue square dynamically with Javascript.
The idea is that both (HTML positioned) squares can have dynamic positions. Im not great with math in this way, so im a bit blank. Sorry i have no start-up code for this formular.
How do i calculate the new rotation angle, so that the red square can be rotated to center point on the blue square?
The black line represents the eyes on the square, as i tried to illustrate on the image.
Upvotes: 1
Views: 300
Reputation: 833
To work out the angle to rotate the square by, you'll need to use some trigonometry. First, we work out the vertical and horizontal distances between the centres of the squares, then we get the inverse tangent to get the angle you need to rotate by. I'm assuming you want the top border to face the blue square.
// Get the two squares
var red = $('#red');
var blue = $('#blue');
// Get the x and y co-ordinates of the centres of the red and blue squares
var redX = red.offset().left + red.width() / 2;
var redY = red.offset().top + red.height() / 2;
var blueX = blue.offset().left + blue.width() / 2;
var blueY = blue.offset().top + blue.height() / 2;
// Get the offsets
var X = blueX - redX;
var Y = blueY - redY;
// Add an extra 90 degrees to the angle so the top border faces the blue square
var angle = Math.atan2(Y, X) + Math.PI / 2;
// Rotate the red square by editing its CSS
red.css({'-webkit-transform' : 'rotate('+ angle +'rad)',
'-moz-transform' : 'rotate('+ angle +'rad)',
'-ms-transform' : 'rotate('+ angle +'rad)',
'transform' : 'rotate('+ angle +'rad)'});
Here's a diagram of how the maths works:
X
__________B
| /
| / X = B(x) - R(x)
| / Y = B(y) - R(y)
| / tan(A) = Y / X
Y | / A = atan(Y / X)
| /
|__/
|A/
|/
R
I've done a Codepen with an example of how this works as well. Hope this helps!
Upvotes: 2