Search code examples
javascriptraphaelgraphael

How to draw a simple path with animation in Raphaël.js


I am trying to draw a simple path with animation from start to end of a path using the Raphaël.js library at this Demo.

var canvas = Raphael('canvas', 900, 648);
var pathString = "M 200,200 L200,10 L100,10";

$('#start').click(function(e) {
       var line = canvas.path(pathString).attr({ stroke: "#000" });
       line.animate({     },5000);
});

but not sure how to use the animate() function here. How can I achieve this?


Solution

  • There may be a better way to do this, but here is the best I can find: getSubpath allows retrieving a segment of a path. By implementing a custom property which can be animated, we can control the path based on the value of this property:

    var canvas = Raphael('canvas', 900, 648);
    var pathString = "M 200,200 L200,10 L100,10";
    
    canvas.customAttributes.subpath = function (from, to) {
      from = Math.floor(from);
      to = Math.floor(to);
      if(to < from)
        to = from;
      return {path: this.parentPath.getSubpath(from, to)};
    };
    
    $('#start').click(function(e) {
      canvas.clear();
      // Create an invisible full representation of the path
      var completeLine = canvas.path(pathString).attr({ 'stroke-opacity': 0 });
      var len = completeLine.getTotalLength(pathString);
    
      // Create a partial representation of the path
      var line = canvas.path(pathString);
      line.parentPath = completeLine;
      line.attr({ stroke: "#000", subpath: [0, 0]});
    
      // Animate using our custom subpath attribute from 0 to the length of the full path
      line.animate({ subpath: [0, len] }, 5000);
    });
    

    https://jsfiddle.net/r40k0kjv/5/