在for循环中更改SVG行的strokeDashoffset

时间:2015-03-10 18:59:06

标签: javascript html5 animation svg

我试图为一条线扩展设置动画。我已经在css中使用它,但我需要在javaScript中完成它,因为这是我可以获得路径长度的唯一方法,这是我需要的。 我觉得我非常接近,但它不起作用! 有任何想法吗?

以下是我的代码。如你所见,我得到路径的长度,并给它一个这个长度的strokeDashArray。这意味着该线将是虚线,但是破折号正在填满整条线。诀窍是减少strokeDashoffset值,因为它决定了破折号的起始位置。因此,如果它也从pathLength开始,则该行将完全不可见,并且减小该值将显示该路径。

我知道这是可能的btw :)如上所述,我已经在css工作了。

var element = document.getElementById("animpath");
var pathLength = element.getTotalLength();

element.style.strokeDasharray = pathLength;
element.style.strokeDashoffset = pathLength;

function animateRoute (e) 
{
e.style.strokeDashoffset = e.style.strokeDashoffset - 100;
}

for (i = 0; i < 100; i++)
{
animateRoute(element);
}

提前致谢!

1 个答案:

答案 0 :(得分:7)

代码:

function animateRoute (e) 
{
   e.style.strokeDashoffset = e.style.strokeDashoffset - 100;
}

for (i = 0; i < 100; i++)
{
   animateRoute(element);
}

基本等同于

e.style.strokeDashoffset = e.style.strokeDashoffset - 10000;

因为循环遍历所有迭代而不给浏览器更新页面的机会。

要解决这个问题,请在循环中执行一步,然后调用setTimeout()告诉浏览器稍微返回给我们,以便我们可以进行下一次迭代。

var element = document.getElementById("animpath");
var pathLength = element.getTotalLength();

element.style.strokeDasharray = pathLength;
element.style.strokeDashoffset = pathLength;

function animateRoute(e, len) 
{
  // Each step we decrement the dash offset
  len -= 10;
  if (len < 0)
    len = 0;  // clamp to minimum 0

  element.style.strokeDashoffset = len;

  // We need to stop looping when the length gets to 0
  if (len > 0) {
    // Do another step
    setTimeout(function() { animateRoute(e, len); }, 10);
  }
}

animateRoute(element, pathLength);
<svg viewBox="-10 -10 420 120">
  
    <path id="animpath" d="M 0 0 L 400 10 0 20 400 30 0 40 400 50 0 60 400 70 0 80 400 90 0 100"
          stroke="black" stroke-width="3" fill="none"/>
  
</svg>

相关问题