将 1 个正方形旋转到第二个正方形的中心点

rotate 1 square to center point on second square

我正在尝试弄清楚如何 "center point" 蓝色方块上的红色大方块 Javascript。

想法是两个(HTML 定位的)方块都可以有动态位置。我在这方面不太擅长数学,所以我有点空白。抱歉,我没有这个公式的启动代码。

如何计算新的旋转角度,使红色方块旋转到蓝色方块的中心点?

黑线代表广场上的眼睛,正如我试图在图片上说明的那样。

要计算出正方形旋转的角度,您需要使用一些三角函数。首先,我们计算出正方形中心之间的垂直和水平距离,然后我们计算反正切值以获得需要旋转的角度。我假设您希望顶部边框面向蓝色方块。

// 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

我已经完成了一个 Codepen,并提供了一个例子来说明它是如何工作的。 希望这对您有所帮助!