CSS缩放SVG时移动元素

6

我正在尝试制作一个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);
  }
}
<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>

3个回答

9
为了避免在 transform-origin 上设置像素值,你也可以将 transform-box 调整为相对于元素而不是整个 SVG 来设置 transform-origin

.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);
  }
}
<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>


运行得很好,比计算矩形新中心点容易得多。 - L4marr

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);
  }
}
<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>


1
你可以通过动画 width 来实现所需的效果:

.svg {
  width: 40%;
}

#charge {
  width: 10px;
  height: 80px;
  animation: charge 1s ease infinite;
}

@keyframes charge {
  0% {
    width: 0;
  }
  100% {
    width: 180px;
  }
}
<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" x="10" y="10" fill="#0071BC"/>
  </svg>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接