在for循环中更改SVG行的strokeDashoffset [英] Change strokeDashoffset of a SVG line in a for loop

查看:87
本文介绍了在for循环中更改SVG行的strokeDashoffset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为扩展的行设置动画。我已经在CSS中使用它了,但是我需要在javaScript中使用它,因为那是获得所需长度的唯一方法。
我想我已经很近了,但是没有用!
有什么想法吗?

I'm trying to animate a line expanding. I already have it in css, but I need to do it in javaScript, because that is the only way I can get the lenght of the path, which I need. I think I'm very close but it's not working! Any ideas?

以下是我的代码。如您所见,我得到了路径的长度,并为其指定了一个strokeDashArray。这意味着该行将变为虚线,但破折号将填满整个行。技巧是减小strokeDashoffset值,因为这确定了破折号的起始位置。因此,如果它也从pathLength开始,则该行将完全不可见,减小该值将显示该路径。

Following is my code. As you can see I get the length of the path, and give it a strokeDashArray of that length. That means the line will be dashed, but the dash is filling the entire line. The trick is to decrease the strokeDashoffset value, because that determines where the dash starts. So if that also starts at pathLength, the line will be completely invisible, and decreasing the value will reveal the path.

我知道这可能是顺便说一句:)如前所述,我已经可以在CSS中使用它了。

I know this is possible btw :) As said, I already have it working in 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);
}

谢谢!

推荐答案

代码:

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;

因为循环鞭打了所有迭代,而没有给浏览器更新页面的机会。

Because the loop whips through all its iterations without giving the browser a chance to update the page.

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

To get around that, do one step in the loop and then call setTimeout() to tell the browser to come back to us in a little bit so we can do the next iteration.

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>

这篇关于在for循环中更改SVG行的strokeDashoffset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆