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

标签 javascript math formula

我正在尝试弄清楚如何使用 Javascript 动态地将大红色方 block “置于中心点”。

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

如何计算新的旋转 Angular ,使红色方 block 旋转到蓝色方 block 的中心点?

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

enter image description here

最佳答案

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

// 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还有一个例子说明它是如何工作的。 希望这对您有所帮助!

关于javascript - 将 1 个正方形旋转到第二个正方形的中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35801788/

相关文章:

c++ - 矩阵模板库矩阵求逆

algorithm - 行数和列数相等的矩阵

python - 生成点不在对方范围内?

excel - 如何为员工的工作时间添加单位后缀?

javascript - 请有人解释一下这段简短而甜蜜的 JavaScript 代码

javascript - 如何在谷歌地图的infowindows中添加媒体文件(视频)?

javascript - ReactJS - 防止重新渲染 child

javascript - JSDoc 中对象中任意键值的文档结构

excel - 两列中任意两个值之间的最大差值的公式

excel - 具有多个 VLOOKUP 的 SUM 行