How can I animate a progressive drawing of svg path?

前端 未结 4 1346
忘掉有多难
忘掉有多难 2020-11-29 21:37

I want to animate a progressive drawing of a line using only css with svg/canvas and js maximum. An idea of the line I want to draw can be found here



        
4条回答
  •  庸人自扰
    2020-11-29 21:43

    There are three techniques listed in this answer:


    There is an all-SVG solution that involves progressively modifying the stroke-dasharray for the shape to draw a longer and longer 'dash' followed by an enormous gap.

    Demo: http://phrogz.net/svg/progressively-drawing-svg-path-via-dasharray.html

    Relevant code:

    var distancePerPoint = 1;
    var drawFPS          = 60;
    
    var orig = document.querySelector('path'), length, timer;
    orig.addEventListener('mouseover',startDrawingPath,false);
    orig.addEventListener('mouseout', stopDrawingPath, false);
    
    function startDrawingPath(){
      length = 0;
      orig.style.stroke = '#f60';
      timer = setInterval(increaseLength,1000/drawFPS);
    }
    
    function increaseLength(){
      var pathLength = orig.getTotalLength();
      length += distancePerPoint;
      orig.style.strokeDasharray = [length,pathLength].join(' ');
      if (length >= pathLength) clearInterval(timer);
    }
    
    function stopDrawingPath(){
      clearInterval(timer);
      orig.style.stroke = '';
      orig.style.strokeDasharray = '';
    }
    

    Alternatively, you can still use all SVG and choose to build the SVG path one command at a time:

    Demo: http://phrogz.net/svg/progressively-cloning-svg-path.html

    Relevant code:

    // Assumes 'orig' and dup' are SVG paths
    function addNextPathSegment(){
      var nextIndex   = dup.pathSegList.numberOfItems;
      if (nextIndex

    Finally, you may choose to draw your path to an HTML5 canvas by sampling the SVG path periodically and drawing to the canvas. (Note that the SVG path does not need to be displayed for this to happen; you can build an SVG path element entirely in JavaScript and sample it):

    Demo: http://phrogz.net/svg/progressively-drawing-svg-path.html

    Relevant code:

    function startDrawingPath(){
      points = [];
      timer = setInterval(buildPath,1000/drawFPS);
    }
    
    // Assumes that 'orig' is an SVG path
    function buildPath(){
      var nextPoint = points.length * distancePerPoint;
      var pathLength = orig.getTotalLength();
      if (nextPoint <= pathLength){
        points.push(orig.getPointAtLength(nextPoint));
        redrawCanvas();
      } else stopDrawingPath();
    }
    
    function redrawCanvas(){
      clearCanvas();
      ctx.beginPath();
      ctx.moveTo(points[0].x,points[0].y);
      for (var i=1;i

提交回复
热议问题