// 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)'});
这是数学如何工作的图表:
X
__________B
| /
| / X = B(x) - R(x)
| / Y = B(y) - R(y)
| / tan(A) = Y / X
Y | / A = atan(Y / X)
| /
|__/
|A/
|/
R
1 回答
要计算旋转方块的角度,您需要使用一些三角法 . 首先,我们计算出正方形中心之间的垂直和水平距离,然后我们得到反正切以获得旋转所需的角度 . 我假设您希望顶部边框面向蓝色方块 .
这是数学如何工作的图表:
我做了一个Codepen,并举例说明了它是如何工作的 . 希望这可以帮助!