[英]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.