gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:27:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com