【问题标题】:How can I do an SVG Path drawing animation when the stroke has a dasharray?当笔划有 dasharray 时,如何制作 SVG 路径绘制动画?
【发布时间】:2014-05-30 03:30:58
【问题描述】:

希望为下面的 SVG 设置动画,我最初已经开始使用它。但是,我希望它用我定义的点以相反的方向“绘制”第二个 SVG。

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

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

【问题讨论】:

    标签: css svg css-animations


    【解决方案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 中似乎存在问题。如果您为路径长度创建“正确”数量的破折号,它不会完全到达路径的末端。您需要添加额外的。

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

    【讨论】:

    • 你好,不错!我喜欢。不过,它只适用于 chrome... :)
    • 小问题。现在已经修好了。 :)
    猜你喜欢
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2012-12-25
    • 2021-06-25
    • 2013-03-08
    相关资源
    最近更新 更多