调整旋转的元件时计算正确的宽度和高度

问题描述 投票:0回答:2

我创建一个选择工具,其中用户可以扩展并使用选择控制元件转动的HTML元素。旋转的元素和缩放它时,它不旋转,做工精细。我现在有点用数学来扩展其已经旋转的元素丢失。

下面是简化的代码。

// 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";

如何计算新的宽度/高度时元件转动和它的新位置?

一个完整的代码示例将是一个有点太长了,所以我做了显示当前状态,并发出fiddle

感谢您的帮助,联系到必要的数学或代码示例。

javascript css math
2个回答
0
投票

也许getBoundingClientRect是你想要的。

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

你也可以让生活简单,只需使用一个尺度变换?


0
投票

最后,我已经找到了一个可行的解决方案。关键是通过获取当前鼠标的位置和对角来计算新的中心点。现在我旋转两个点恢复到未旋转的状态,并得到界限来使用。相关代码如下所示:

// 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";

updated fiddle(注意,这是更多的概念,并没有生产就绪的解决方案的证明。)

我打开更优雅的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.