【问题标题】:Drawing animation of an arrow in SVG在 SVG 中绘制箭头的动画
【发布时间】:2014-12-26 14:09:30
【问题描述】:

我是 SVG 世界的新手,当我想“绘制”弯曲的箭头时遇到了一些问题。

基本上,我想创建一个类似于this article 中解释的动画,但在路径的末尾有一个形状以显示箭头。

以下是我用于直箭头的代码:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<defs>
  <marker
    id="arrow"
    orient="auto"
    viewBox="0 0 10 10"
    markerWidth="3"
    markerHeight="4"
    markerUnits="strokeWidth"
    refX="1" refY="5">
   <polyline points="0,0 10,5 0,10 1,5" fill="black" />
  </marker>
</defs>

<path
    id="line"
    marker-end="url(#arrow)"
    stroke-width="3"
    fill="none"
    stroke="black">

    <animate
        dur="2s"
        repeatCount="indefinite"
        attributeName="d"
        values="M10,10 L10,10; M10,10 L45,25;" />
</path>

加上一点 CSS:

#line
{
   stroke-dasharray: 5;
  stroke-dashoffset: 10;
  -webkit-animation: draw 1s linear infinite;
}

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

结果如下:

这很酷,但现在我想要一个弯曲的箭头。所以我更新了动画标签,如下所示:

<animate
        dur="2s"
        repeatCount="indefinite"
        attributeName="d"
        values="M7,121 C7,121 7,121 7,121; M7,121 C66,4 143,75 147,125" />

我刚刚更改了动画路径,以便获得弯曲的路径。但结果如下:

我认为这很合乎逻辑,但这不是我想要的。标记当前正在直线移动;它应该遵循绘图路径。

说实话,我不知道该怎么做,任何建议都会很棒:)

你可以找到a JSFiddle here

如您所见,这些实验中没有使用 JS,如果我们可以避免使用这种语言而只使用 SVG+CSS,那就太好了。

提前致谢!

【问题讨论】:

    标签: css animation svg


    【解决方案1】:

    我想你可能会发现这篇关于 svg 线条动画的文章非常有用: https://css-tricks.com/svg-line-animation-works/

    CSS:

    .path {
       stroke-dasharray: 1000;
       stroke-dashoffset: 1000;
       animation: dash 5s linear alternate infinite;
    }
    
    @keyframes dash {
      from {
         stroke-dashoffset: 1000;
      }
      to {
         stroke-dashoffset: 0;
      }
    }
    

    实际演示:http://codepen.io/chriscoyier/pen/bGyoz

    其中有一个关于 JavaScript 和确定要绘制的线条长度的警告。如果你不想使用 JS,你可以通过更新 dasharray 和 dashoffset 值来确定动画的长度。

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 感谢@Adam,我已经用 Chris 的代码更新了示例。
    猜你喜欢
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2019-07-26
    • 1970-01-01
    • 2010-10-22
    • 2013-10-20
    • 2020-06-25
    相关资源
    最近更新 更多