【问题标题】:Get the width and height of rotated object after transform获取变换后旋转对象的宽高
【发布时间】:2013-06-09 10:28:16
【问题描述】:

这个问题是问题的后续:width/height after transform

我发布了一个新问题,因为该问题只解决了宽度而不是高度。 公式:

var x = $('#box').width()*Math.cos(rotationAngle) 
      + $('#box').height()*Math.sin(rotationAngle);

宽度很好,计算高度的等效公式是什么?

谢谢。

【问题讨论】:

  • 猜一猜,你可能会猜对。这是微不足道的(尤其是从您拥有的方程式来看),更不用说整个互联网了。
  • 我曾尝试在 cos 和 sin 之间切换,但没有成功...我很高兴听到你的回答 :)
  • 切换 cos 和 sin 答案,但我会说你得到的公式缺少必要的 Math.abs 调用。正如我所说,它遍布互联网。

标签: javascript jquery css


【解决方案1】:

这是我想出的最有效的公式:

var h = $(obj).height() * Math.abs(Math.cos(deg)) + $(obj).width() * Math.abs(Math.sin(deg));
var w = $(obj).width() * Math.abs(Math.cos(deg)) + $(obj).height() * Math.abs(Math.sin(deg));

【讨论】:

  • 该死的角度是弧度,而我是在度数大声笑
  • 你能从角度和 h & w 找到原始的高度和宽度吗?公式是什么?
【解决方案2】:

以下代码将在 JavaScript 中计算旋转对象的边界框。

var obj = document.getElementById("obj"); // Get object
var bx = obj.clientWidth; // Width of rectangle
var by = obj.clientHeight; // Height of rectangle
var t = /[0-9]+/.exec(obj.style.transform)[0] * Math.PI / 180; // Convert to radians

var x = Math.sin(t) * by + Math.cos(t) * bx; // The bounding box width
var y = Math.sin(t) * bx + Math.cos(t) * by; // The bounding box height

document.write(x.toFixed(2), " ", y.toFixed(2)); // The width and height of finished bounding box of item rounded to 2 decimal places
<div id="obj" style="width: 200px; height: 200px; transform: rotate(30deg); background: red;"></div>

【讨论】:

    【解决方案3】:

    如果角度值为负,@ChiMo 的解决方案将不起作用。 固定版本:

    var obj = document.getElementById("obj"); // Get object
    var bx = obj.clientWidth; // Width of rectangle
    var by = obj.clientHeight; // Height of rectangle
    var t = /[0-9]+/.exec(obj.style.transform)[0] * Math.PI / 180; // Convert to radians
    var x = Math.sin(t) * by + Math.cos(t) * bx; // The bounding box width
    var y = Math.sin(t) * bx + Math.cos(t) * by; // The bounding box height
    
    document.write(x.toFixed(2), " ", y.toFixed(2)); // The width and height of finished bounding box of item rounded to 2 decimal places
    
    var wrapper = document.getElementById("wrapper"); // Get object
    wrapper.style.width = Math.round(x) + 'px';
    wrapper.style.height = Math.round(y) + 'px';
    #obj {
      width: 100px;
      height: 100px;
      background-color: red;
    }
    
    #wrapper {
      border: 1px solid black;
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      justify-content: center;
    }
    <div id="wrapper">
      <div id="obj" style="transform: rotate(-30deg)"></div>
    </div>

    【讨论】:

      【解决方案4】:

      嗯,您之前的问题涉及一个正方形。正方形的尺寸始终相同。所以,除非有什么奇怪的事情发生,否则你的高度应该和你的宽度完全一样。

      【讨论】:

      • 是的,原来的问题涉及正方形,我问的是矩形。
      猜你喜欢
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多