当笔划有dasharray时,如何进行SVG路径绘制动画?

时间:2014-05-28 12:14:32

标签: css3 svg css-animations

想要为下面的SVG制作动画,我最初开始工作。但是,我希望它能够画出'第二个相反方向的SVG,用我定义的点。

我有什么方法可以做到这一点?用点从左到右有效地绘制我的形状。

Codepen:http://codepen.io/anon/pen/gFcAz

1 个答案:

答案 0 :(得分:1)

正常的短划线偏移动画技巧实际上只适用于实线。

这是我设法使用CSS动画的最接近的地方。

http://jsfiddle.net/L4zCY/

不幸的是,破折号爬行是因为您无法控制stroke-dashoffset的步进速率。如果你可以一次10步,那么破折号就不会移动。

所以我认为唯一的解决方法就是使用Javascript。

var path = document.querySelectorAll("svg path").item(0);
animateDashedPath(path);

/*
 * Animates the given path element.
 * Assumes the path has a "5 5" dash array.
 */
function animateDashedPath(path)
{
  var pathLength = path.getTotalLength();
  var animationDuration = 2000;
  var numSteps = Math.round(pathLength / (5+5) + 1);
  var stepDuration = animationDuration / numSteps;

  // Build the dash array so we don't have to do it manually
  var dasharray = [];
  while (numSteps-- > 0) {
    dasharray.push(5);
    dasharray.push(5);
  }
  dasharray.push(pathLength);

  // Animation start conditions
  path.setAttribute("stroke-dasharray", dasharray.join(" "));
  path.setAttribute("stroke-dashoffset", -pathLength);

  // We use an interval timer to do each step of the animation   
  var interval = setInterval(dashanim, stepDuration);

  function  dashanim() {
    pathLength -= (5+5);
    path.setAttribute("stroke-dashoffset", -pathLength);
    if (pathLength <= 0) {
      clearInterval(interval);
    }
  }
}

Demo here

<强>更新

看起来FF中存在问题。如果您创建&#34;右&#34;路径长度的短划线数,它不会完全到达路径的末端。你需要额外添加。

A version of the demo that works properly on FF is here