SVG子元素上的CSS转换原点问题

时间:2019-05-21 16:44:00

标签: html css animation svg

尝试缩放子元素时,转换原点出现问题。

在尝试缩放较大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>

1 个答案:

答案 0 :(得分:2)

您需要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>

相关问题