[英]Get the width and height of rotated object after transform
這個問題是這個問題的后續: width/height after transform 。
我發布了一個新問題,因為該問題只解決了寬度而不是高度。 公式:
var x = $('#box').width()*Math.cos(rotationAngle)
+ $('#box').height()*Math.sin(rotationAngle);
適用於寬度,計算高度的等效公式是什么?
謝謝。
這是我想出的最好的工作公式:
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));
下面的代碼將計算出 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>
如果角度值為負,@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>
好吧,你之前的問題涉及一個正方形。 正方形始終具有相同的尺寸。 所以,除非有一些時髦的事情發生,否則你的高度應該和你的寬度完全一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.