【问题标题】:CSS: Changing width/height after rotation in one direction onlyCSS:仅在一个方向旋转后更改宽度/高度
【发布时间】:2021-05-28 15:33:22
【问题描述】:

我的最终目标是一个可拖动、可调整大小、可缩放和可旋转的元素,就像 https://daybrush.com/moveable/ 上的示例一样,仅使用 css 宽度、高度和变换:旋转、平移。

假设我有一个带有以下 css 的 div:

.rect {
  background-color: red;
  width: 200px;
  height: 100px;
  top:100px;
  left:100px;
  position: absolute;
  transform: rotate(0deg);
  
}
<div class="rect"></div>

如果我想将 div 水平向左调整大小,我只需将宽度更改 x 像素。如果我想将其更改为右侧,我只需将宽度更改 x 个像素,然后平移(-xpx,0)。

但是如果我改变角度呢?通过尝试很多东西,我发现了一些 x 和 y 值可以转换为相应的角度,但是我觉得有一种比猜测更直接的方法。例如:对于 90 度,如果我想向左调整 x px,我会平移 (-x0.5px, x0.5px)。

更多:如果我想同时改变宽度和高度怎么办?

P.S.:我宁愿避免使用库,transform: scale 或 svg

P.P.S:Example进一步演示问题,只是改变宽度:

.rect {
  background-color: red;
  width: 200px;
  height: 100px;
  top:100px;
  left:100px;
  position: absolute;
  transform: rotate(45deg);
  animation: expand 5s infinite
}

@keyframes expand {
  from {width: 200px;}
  to {width: 2000px;}
}
<div class="rect"></div>

固定,拉伸原始矩形的左侧(现在旋转 90 度后向上):

.rect {
  background-color: red;
  width: 200px;
  height: 100px;
  top:100px;
  left:100px;
  position: absolute;
  transform: rotate(90deg);
  animation: expand 3s infinite
}

@keyframes expand {
  from {
    width: 200px;
    }
  to {
    width: 800px;
    transform: rotate(90deg) translate(-300px, 300px);
    }
}
<div class="rect"></div>

【问题讨论】:

  • 检查this answer 是否有帮助。在那里,我正在单独计算转换的转换矩阵,并将不同的转换组合在一起。

标签: css math geometry linear-algebra trigonometry


【解决方案1】:

您可以对同一个对象应用多个转换,它们将按照您指定的顺序组合。先移动后旋转,不同于先旋转后移动。

.rect {
  background-color: red;
  width: 200px;
  height: 100px;
  top:100px;
  left:100px;
  position: absolute;
}
.t1 {
  background-color: #40d04080;
  /* green shaded rectangle: rotate after translation */
  transform: translate(2cm, 0) rotate(30deg);
}

.t2 {
  background-color: #f0404080;
  transform: rotate(30deg);
}

.t3 {
  background-color: #4040f080;
  /* blue shaded rectangle: translate after rotation */
  transform: rotate(30deg) translate(2cm, 0) ;
}
<div class="rect t1"></div>
<div class="rect t2"></div>
<div class="rect t3"></div>

【讨论】:

  • 感谢您的回答,但我不明白这与我的问题有什么关系。此外,应用函数的顺序是right to left 所描述的问题是关于元素在更改大小时从原始位置“移动”,需要平移以抵消该移动。问题是找到那个偏移量。
  • 我的理解假设一个transforma A和一个transforma B,在CSS中指定为A B,它们会从左到右依次相乘。即你有一个对象X,你应用A,然后你得到A X,然后你对这个转换结果应用转换B,然后你将得到B (A X),即等效(B A) X,得到的转换(B A) .你同意吗?
  • 对于第二个问题,您可能需要明确设置transform-origin
猜你喜欢
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多