簡體   English   中英

調整旋轉元素的大小時計算正確的寬度和高度

[英]Calculate correct width and height when resizing a rotated element

我正在創建一個選擇工具,用戶可以在其中使用選擇控件元素縮放和旋轉HTMLElement。 旋轉元素並在不旋轉時縮放它,效果很好。 我現在對使用數學運算來縮放已經旋轉的元素有些迷惑。

這是簡化的代碼。

// rotating the element
selection.style.transform = "rotate(" + degrees + "deg)";

...

// scaling the element
var left = selection.offsetLeft;
var top = selection.offsetTop;
selection.style.width = (e.clientX - left) + "px";
selection.style.height = (e.clientY - top) + "px";

元素旋轉時如何計算新的寬度/高度及其新位置?

完整的代碼示例可能太長了,因此我擺弄了一下當前狀態和問題。

感謝您的幫助,鏈接到必要的數學或代碼示例。

也許getBoundingClientRect是您想要的。

 console.log(document.querySelector('.rotate').getBoundingClientRect()) 
 .rotate { width: 80px; height: 50px; background: blue; transform: rotate(45deg); } 
 <div class="rotate"></div> 

您還可以使生活變得輕松,僅使用比例轉換?

終於,我找到了一個可行的解決方案。 關鍵是要通過獲取當前鼠標位置和對角來計算新的中心點。 現在,我將兩個點都旋轉回其未旋轉狀態,並獲得了要使用的范圍。 相關代碼如下:

// the current rotation angle in degrees
angle = me.angle;
// the current mouse point (dragging a selection control)
var mousePoint = new Point(e.clientX, e.clientY);
// Get opposite point. Rotate it to get the visual position
var topLeft = new Point(left, top).rotate(center, angle);
// calculate the new center 
var centerPoint = mousePoint.getMiddle(topLeft);
// rotate the opposite point back around the new center
var topLeftRotated = topLeft.rotate(centerPoint, -angle);
// rotate the mouse point around the new center.
var mousePointRotated = mousePoint.rotate(centerPoint, -angle);

// now we have the top left and lower right points and 
// can calculate the dimensions
var x1 = topLeftRotated.x;
var x2 = mousePointRotated.x;
var w = x2-x1;
var y1 = topLeftRotated.y;
var y2 = mousePointRotated.y;
var h = y2-y1;

me.selection.style.width = w + "px";
me.selection.style.height = h + "px";
me.selection.style.left = x1 + "px";
me.selection.style.top = y1 + "px";

請參閱更新的小提琴 (注意。這更多是概念證明,尚無生產就緒的解決方案。)

我願意接受更優雅的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM