将div旋转到js中的特定高度 [英] Rotate a div to certain height in js

查看:52
本文介绍了将div旋转到js中的特定高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将div旋转到某个高度假设10像素.我可以将div绕360度旋转.我需要div接触线的角度.

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.

推荐答案

您可以应用圆的坐标公式:(x-a)²+(y-b)²=r².因为我们只对角度感兴趣,所以可以将圆放置在原点上,而忽略 a b ,这使计算更加简单.

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.

在图像中,绿色项目是已知的,青色项目是帮助程序,红色项目是更改/结果.符号与下面的代码片段中的变量名称匹配.

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²必须为> = 0,否则距直线(d)的距离太大,并且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.

这篇关于将div旋转到js中的特定高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆