Search code examples
javascriptrotationangle

Rotate a div to certain height in js


How to rotate a div to certain height suppose 10px. I can rotate a div otherwise around 360 degrees. I need the angle by which the div would touch the line.enter image description here


Solution

  • You can apply the coordinate formula of the circle: (x - a)² + (y - b)² = r². Because we've interest in the angle only, we can position the circle on the origin, and ignore a and b, which makes the calculation much more simple.

    The geometry the solution is based on.

    In the image, the green items are known, the cyan items are helpers, and the red items are the changes/results. Symbols are matching the variable names in the below code snippet.

    const
      w = 50,    // Halfwidth of the div
      h = 25,    // Halfheight of the div
      d = 10,    // The distance between the line and the box
      y = h + d, // The final Y-coordinate of the box corner
      R = w ** 2 + h ** 2,         // The square of the length of the "radius line"
      x = Math.sqrt(R - y ** 2),   // The final X-coordinate of the box corner
      a = Math.atan2(h, w),        // The original angle of the "radius line"
      b = Math.atan2(y, x),        // The new angle of the "radius line"
      r = (b - a) * 180 / Math.PI, // The rotation angle
      box = document.querySelector('.box');
    
    box.style.transform = 'rotate(' + r + 'deg)';
    .line {
      position: fixed;
      box-sizing: border-box;
      top: 10px;
      left: 0px;
      width: 100%;
      height: 1px;
      border-bottom: 1px solid #000;
    }
    .box {
      position: fixed;
      top: 20px;
      width: 100px;
      height: 50px;
      background: red;
    }
    <div class="line"></div>
    <div class="box"></div>

    R - y² must be >= 0, otherwise the distance to the line (d) is too large and the corner of the div never meets the line. You can swap the direction by negating the rotation angle.