我试图弄清楚如何用Javascript动态地在蓝色方块上“中点”大红方。
其思想是,这两个(HTML定位)方块可以有动态的位置。我不擅长这种方式的数学,所以我有点空白。对不起,我没有这个公式的启动代码。
如何计算新的旋转角度,使红方块可以旋转到蓝色方格的中心点?
黑线代表了广场上的眼睛,就像我试图在图像上说明的那样。

发布于 2016-03-04 17:39:27
要计算出旋转正方形的角度,你需要使用一些三角函数。首先,我们计算出正方形中心之间的垂直距离和水平距离,然后求出逆切线,得到需要旋转的角度。我猜你想让最上面的边框朝向蓝色的广场。
// 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我做了一个科德芬,并举例说明了它是如何工作的。希望这能有所帮助!
https://stackoverflow.com/questions/35801788
复制相似问题