css 缩放 SVG 移动元素

Jac*_*cob 4 css svg

我正在尝试制作 svg 动画,正如演示所示,当我缩放 svg 的电荷填充时,它被推到容器的左边缘。

是否可以在 svg 中保留路径的 x,y 属性?还是我的 svg 无法正确设置动画?

.svg {
  width: 40%;
}

#charge {
  /* animation: charge 1s ease infinite; */
  transform: scaleX(0.1);
}

@keyframes charge {
  0% {
    transform: scaleX(0.1);
  }
  100% {
    transform: scale(1);
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class="svg">
  <svg xmlns="http://www.w3.org/2000/svg" id="battery_1_" x="0px" y="0px" viewBox="0 0 214 100">
                <polygon id="outline" points="214,22.5 200,22.5 200,0 0,0 0,100 200,100 200,77.5 214,77.5"/>
                <rect id="charge" width="180" height="80" x="10" y="10" fill="#0071BC"/>
              </svg>
</div>
Run Code Online (Sandbox Code Playgroud)

Tem*_*fif 6

为了避免在 上设置像素值,transform-origin您还可以调整transform-box以具有transform-origin相对于元素而不是整个 SVG:

.svg {
  width: 40%;
}

#charge {
  transform-origin: left;
  transform-box:fill-box;
  animation: charge 1s ease infinite;
  transform: scaleX(0.1);
}

@keyframes charge {
  0% {
    transform: scaleX(0.1);
  }
  100% {
    transform: scale(1);
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class="svg">
  <svg xmlns="http://www.w3.org/2000/svg" id="battery_1_" x="0px" y="0px" viewBox="0 0 214 100">
     <polygon id="outline" points="214,22.5 200,22.5 200,0 0,0 0,100 200,100 200,77.5 214,77.5"/>
     <rect id="charge" width="180" height="80" x="10" y="10" fill="#0071BC"/>
   </svg>
</div>
Run Code Online (Sandbox Code Playgroud)


bon*_*onk 3

您可以使用该transform-origin属性来更改变换元素的位置。默认值为 50%、50%,使变换从元素的中间开始。

.svg {
  width: 40%;
}

#charge {
  transform-origin: 10px;
  animation: charge 1s ease infinite;
  transform: scaleX(0.1);
}

@keyframes charge {
  0% {
    transform: scaleX(0.1);
  }
  100% {
    transform: scale(1);
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class="svg">
  <svg xmlns="http://www.w3.org/2000/svg" id="battery_1_" x="0px" y="0px" viewBox="0 0 214 100">
     <polygon id="outline" points="214,22.5 200,22.5 200,0 0,0 0,100 200,100 200,77.5 214,77.5"/>
     <rect id="charge" width="180" height="80" x="10" y="10" fill="#0071BC"/>
   </svg>
</div>
Run Code Online (Sandbox Code Playgroud)