反转SVG线条绘制动画

时间:2015-09-09 15:44:15

标签: css animation svg css-animations

我正试图扭转这个SVG线的动画效果。我需要从左到右绘制线条,但只能让它从右到左工作。我试图改变插图画家的终点,但这只会导致它从两面画出来。我该怎么做呢?您可以在此处查看动画:http://mckeever02.github.io/voxbit/

这是SVG:

<svg viewBox="0 0 759.7 234.2">
    <path class="phone-line" stroke="#fff" stroke-width="4" stroke-dashoffset="20" fill="none" class="st0" d="M755.6,229.7H540.1c-31.9,0-57.6-27-57.6-58.9l0-5.8V61.6c0-31.9-26.1-58-58-58h-40.8h-7.9H335
    M755.6,229.7H540.1c-31.9,0-57.6-27-57.6-58.9l0-5.8V61.6c0-31.9-26.1-58-58-58h-40.8h-7.9H335
        c-31.9,0-58,26.1-58,58v103.3v6.8c0,31.9-26.1,58-58,58H11.55" />
  </svg>

和CSS动画:

.phone-line {
  stroke-dasharray:1400;
  -webkit-animation: draw 4s ease-in;
}

@-webkit-keyframes draw {
  from {
    stroke-dashoffset: 1400;
  }
  to {
    stroke-dashoffset: 0;
  }
}

1 个答案:

答案 0 :(得分:21)

正如您所知,stroke-dasharray属性会创建一个虚线图案。当该值被指定为1400时,表示短划线的长度和短划线之间的间距为1400.即0到1400,该线将存在,并且从1400到2800将存在短划线。

现在,当您将stroke-dashoffset1400更改为0时,它会从一个方向进入视图。最初偏移量为1400,因此只有破折号可见(无线)。当偏移量设置为0时,短划线向左移动,线条(从0到1400出现)缓慢进入视野。

从另一个方向执行此操作的简单方法是将其从1400设置为2800。完成此操作后,当线条(从2800到4200出现)缓慢进入视野时,短划线向右移动。

&#13;
&#13;
.phone-line {
  stroke-dasharray: 1400;
  animation: draw 4s ease-in;
}
@keyframes draw {
  from {
    stroke-dashoffset: 1400;
  }
  to {
    stroke-dashoffset: 2800;
  }
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<svg viewBox="0 0 759.7 234.2">
  <path class="phone-line" stroke="#000" stroke-width="4" stroke-dashoffset="20" fill="none" class="st0" d="M755.6,229.7H540.1c-31.9,0-57.6-27-57.6-58.9l0-5.8V61.6c0-31.9-26.1-58-58-58h-40.8h-7.9H335
    M755.6,229.7H540.1c-31.9,0-57.6-27-57.6-58.9l0-5.8V61.6c0-31.9-26.1-58-58-58h-40.8h-7.9H335
        c-31.9,0-58,26.1-58,58v103.3v6.8c0,31.9-26.1,58-58,58H11.55" />
</svg>
&#13;
&#13;
&#13;

另一种方法(如Paul LeBeau中的comments所述)是将其设置为-14000的动画。这也产生与上述代码段相同的输出。

&#13;
&#13;
.phone-line {
  stroke-dasharray: 1400;
  animation: draw 4s ease-in;
}
@keyframes draw {
  from {
    stroke-dashoffset: -1400;
  }
  to {
    stroke-dashoffset: 0;
  }
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<svg viewBox="0 0 759.7 234.2">
  <path class="phone-line" stroke="#000" stroke-width="4" stroke-dashoffset="20" fill="none" class="st0" d="M755.6,229.7H540.1c-31.9,0-57.6-27-57.6-58.9l0-5.8V61.6c0-31.9-26.1-58-58-58h-40.8h-7.9H335
    M755.6,229.7H540.1c-31.9,0-57.6-27-57.6-58.9l0-5.8V61.6c0-31.9-26.1-58-58-58h-40.8h-7.9H335
        c-31.9,0-58,26.1-58,58v103.3v6.8c0,31.9-26.1,58-58,58H11.55" />
</svg>
&#13;
&#13;
&#13;

  

注意:我认为理想的方法是将path本身的方向从左侧开始,然后向右移动而不是从右向左移动。这只是一个简单的解决方法,可以在不改变path的情况下反转方向。