首页 > 解决方案 > 寻找带有 CSS 的动画 SVG

问题描述

我想为我的 SVG 图标设置动画。已经做到了,但我错过了一些东西。我是animationCSS新手

问题是进入网站时SVG的位置不对。此外,当 SVG 执行动画(悬停动画)时,就好像 SVG“div”的尺寸完全改变并再次重新缩放。

如何将 SVG 置于其初始的“十字”形状并让它在自己的轴上旋转而不会丢失其主要尺寸?

#logo{
    animation-name: spin;
    animation-duration: 4000ms;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
    transform-origin: center;
    animation-play-state: paused;
}
    
svg:hover #logo{
    animation-play-state: running;
}

@keyframes spin{
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
}
<div class="logo">
  <svg  width="35px" height="35px" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px viewBox="0 0 40 40" style="enable-background:new 0 0 40 40;" xml:space="preserve">
     <g>
        <rect id="logo" x="16.57" y="-4.86" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -8.2843 20)" width="6.86" height="49.71"/>
     </g>
     <g>
        <rect id="logo" x="-4.86" y="16.57" transform="matrix(0.7071 -0.7071 0.7071 0.7071 -8.2843 20)" width="49.71" height="6.86"/>
     </g>
   </svg>  
</div>

标签: htmlcssanimationsvg

解决方案


这是一个例子。基本上我删除了变换,只使用宽度/高度和 x/y 数学。

基本上你创建一个你想要的大小的视图框。我将其保留为 80 80,因为它的尺寸比矩形宽度大。您可以随意使用这些数字。这里的技巧是计算 x 和 y 轴。

x = viewboxX/2 - 宽度/2

y = viewBoxX/2 - 宽度/2

一旦弄清楚了,那么对于第二个正方形,我只是将宽度翻转为高度,将 x 翻转为 y,然后你就得到了你的十字架

#logo{
            animation-name: spin;
            animation-duration: 4000ms;
            animation-iteration-count: infinite;
            animation-timing-function: linear;
            transform-origin: center;
            animation-play-state: paused;
            }

            svg:hover #logo{
            animation-play-state: running;}

            @keyframes spin{
            from {
              transform: rotate(0deg);
            }
            to {
              transform: rotate(360deg);
            }}
  <div class="logo">
            <svg width="100px" height="100px" version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="40px" y="40px" viewBox="0 0 80 80" style="enable-background:new 0 0  40 40;" xml:space="preserve">
             <g id="logo">
                <rect x="15.14" y="36.57" width="49.71" height="6.86"/>
                <rect x="36.57" y="15.14" width="6.86" height="49.71"/>
             </g>          
            </svg> 
         </div>
        


推荐阅读