首页 文章

旋转1平方到第二个方块的中心点

提问于
浏览
1

我试图弄清楚如何用Javascript动态地“中心点”蓝色方块上的大红色方块 .

这个想法是两个(HTML定位)方块都可以有动态位置 . 我用这种方式对数学不太好,所以我有点空白 . 对不起,我没有这个公式的启动代码 .

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

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

enter image description here

1 回答

  • 2

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

    // 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,并举例说明了它是如何工作的 . 希望这可以帮助!

相关问题