Search code examples
fabricjs

FabricJS Animate Path


I'm trying to smoothly animate a path in FabricJS. I've seen examples of how to animate lines, but nothing about animating paths.

I've been able to iterate through an array of path points to get something functioning, but it's choppy and doesn't work well:

function animateLine(pathArray) {
  var pathString = '';
  var directionLine;

  pathArray.forEach((item, i) => {
    setTimeout(() => {
      pathString = pathString + item + ',';

      canvas.remove(directionLine);
      directionLine = new fabric.Path(pathString, {
        fill: '',
        stroke: 'black',
        strokeDashArray: [5, 5],
        objectCaching: false
      });
      canvas.add(directionLine);

    }, i * 20);
  });

}

animateLine(pathString);

Fiddle here.

I'm looking to do something like this example, but it uses Raphael and I'm hoping to not have to switch libraries.


Solution

  • Was able to figure out a solution with help from one of the mods pointing me to strokeDashOffset.

    var canvas = new fabric.Canvas('c');
    var pathArray = "M78.2,0.1c0,0,9.4,79.1,2.3,117  c-4.5,24.1-31.8,106.2-56.3,108.7c-12.7,1.3-24.2-11.9-16.5-15.5C15,207,40.2,231.1,19,261.7c-9.8,14.1-24.7,31.9-12.5,44.9  c11.3,12,53-36.8,59.2-23.8c8.6,18-40.8,23-28,49.2c14.7,30.4,21.6,39.9,48,58.5c31.3,22,147,66.2,147.2,149.5";
    
    var path = new fabric.Path(pathArray, {
      fill: '',
      stroke: 'black',
      strokeDashArray: [5, 5],
      strokeDashOffset: 0
    });
    canvas.add(path);
    
    function animatePath(path) {
        path.animate('strokeDashOffset', '-=3', {
        duration: 100,
        onChange: canvas.renderAll.bind(canvas),
        onComplete: function(){
            animatePath(path)
        }
        });
    }
    
    animatePath(path);
    

    Fiddle