调整旋转元素的大小时,计算正确的宽度和高度

时间:2019-02-05 10:34:08

标签: javascript css math

我正在创建一个选择工具,用户可以在其中使用选择控制元素缩放和旋转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";

旋转元素时如何计算新的宽度/高度及其新位置?

完整的代码示例可能太长了,所以我制作了fiddle来显示当前状态和问题。

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

2 个答案:

答案 0 :(得分:0)

也许getBoundingClientRect是您想要的。

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

您还可以使生活变得轻松,仅使用比例转换吗?

答案 1 :(得分: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 (注意。这更多是概念证明,尚无生产就绪的解决方案。)

我愿意接受更优雅的解决方案。