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

标签 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显示当前状态和问题。

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

最佳答案

我终于找到了可行的解决方案。关键是通过获取当前鼠标位置和对 Angular 来计算新的中心点。现在,我将两个点都旋转回其未旋转的状态并获得要使用的边界。 相关代码如下所示:

// 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 (注意。这更像是一个概念证明,没有生产就绪的解决方案。)

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

关于javascript - 调整旋转元素大小时计算正确的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54532449/

相关文章:

javascript - 在 jQuery Animate 中获得位置

嵌套列表上的 CSS 计数器重置

c - 求解 C 中的超越方程

python - 将代码 matlab 转换为 python numpy

javascript - 在不发出值的情况下完成的 Rxjs 可观察通过单元测试,但不应该

javascript - 让用户滚动停止scrolltop的jquery动画?

javascript - 镭悬停不起作用

javascript - 从所有跨度中找到最大宽度

c++ - 检查数字是否为质数的更好方法是什么?

javascript - 重新排序列表元素 - jQuery?