动画SVG线过渡

时间:2019-11-20 09:08:29

标签: animation svg

给出两个简单的SVG图标,我该如何动画化它们之间的过渡-理想情况下无需复杂的JavaScript(例如GreenSock;但切换一个类就可以了):

svg {
    width: 10em;
    border: 1px solid #AAA;
    stroke: currentColor;
    stroke-width: 3;
    stroke-linecap: square;
    stroke-linejoin: bevel;
    fill: none;
}
<svg viewBox="0 0 24 24">
    <line x1="3" y1="6" x2="21" y2="6" />
    <line x1="3" y1="18" x2="21" y2="18" />
</svg>

<svg viewBox="0 0 24 24">
    <line x1="9" y1="6" x2="15" y2="12" />
    <line x1="9" y1="18" x2="15" y2="12" />
</svg>

(我假设出于动画目的,两个图标的<line>将合并为一个<svg>。)

根据我自己的研究,浏览了网络上许多看似相互矛盾的文档,CSS transformations在这里是不够的(translate + scale + rotate导致不再推荐使用歪斜的图像)和SMIL(我也很难弄清楚如何使其正常工作)。

1 个答案:

答案 0 :(得分:3)

这可能需要一些调整,但是您可以 使用transform属性使CSS过渡起作用。关键是平移,旋转和缩放的应用顺序。

var toggle = true;

document.addEventListener('click', function() {
  document.querySelector('svg').classList[toggle ? 'add' : 'remove']('arrow');
  toggle = !toggle;
});
svg {
  width: 10em;
  border: 1px solid #aaa;
  stroke: currentColor;
  stroke-width: 3;
  stroke-linecap: square;
  stroke-linejoin: bevel;
  fill: none;
  cursor: pointer;
}

svg line {
  transition: transform 250ms ease-in;
}

.arrow .line-top {
  transform: translate(12px, 0px) rotate(45deg) scale(0.5, 1);
}

.arrow .line-bottom {
  transform: translate(-5px, 5.3px) rotate(-45deg) scale(0.5, 1);
}
click to toggle arrow class <br>
<svg viewBox="0 0 24 24">
    <line class="line-top" x1="3" y1="6" x2="21" y2="6" />
    <line class="line-bottom" x1="3" y1="18" x2="21" y2="18" />
</svg>