【问题标题】:CSS transform origin issue on svg sub-elementsvg子元素上的CSS变换原点问题
【发布时间】:2019-10-08 02:54:50
【问题描述】:

我在尝试缩放子元素时遇到了 transform-origin 的问题。

在尝试缩放较大 svg 中的框的动画时,它使用整个 svg 的变换原点 (0,0),而不是我尝试缩放的元素的中心。

这使它看起来像是“从左上角飞入”,这不是我想要的。我希望让它从元素中心缩放。

如何设置相对于我正在制作动画的特定元素的变换原点,而无需对子元素本身的 (x,y) 位置进行硬编码。

这是我正在处理的问题的一个简单示例

@keyframes scaleBox {
  from {transform: scale(0);}
  to {transform: scale(1);}
  }
  #animated-box {
  	animation: scaleBox 2s infinite;
  }
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" style="
        width: 195px;
    "><defs>
    <style>.cls-1{fill:#7f7777;}.cls-2{fill:#fff;}</style>
    </defs>
    <rect class="cls-1" x="0.5" y="0.5" width="99" height="99"></rect>
    <path d="M99,1V99H1V1H99m1-1H0V100H100V0Z"></path>
    <rect id="animated-box" class="cls-2" x="10.5" y="8.5" width="22" height="6"></rect></svg>

【问题讨论】:

    标签: html css animation svg


    【解决方案1】:

    你需要 transform-b​​ox: fill-box;

    @keyframes scaleBox {
      from {transform: scale(0);}
      to {transform: scale(1);}
      }
      #animated-box {
        transform-box: fill-box;
      	animation: scaleBox 2s infinite;
      }
    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" style="
            width: 195px;
        "><defs>
        <style>.cls-1{fill:#7f7777;}.cls-2{fill:#fff;}</style>
        </defs>
        <rect class="cls-1" x="0.5" y="0.5" width="99" height="99"></rect>
        <path d="M99,1V99H1V1H99m1-1H0V100H100V0Z"></path>
        <rect id="animated-box" class="cls-2" x="10.5" y="8.5" width="22" height="6"></rect></svg>

    【讨论】:

    • 工作就像一个魅力,现在我还可以添加 transform-origin: 50% 50% 以使其正确居中。谢谢!
    猜你喜欢
    • 2017-04-15
    • 2016-04-26
    • 1970-01-01
    • 2021-11-19
    • 2018-01-26
    • 1970-01-01
    • 2021-08-03
    相关资源
    最近更新 更多