Search code examples
animationpaperjs

Path smooth fading in paperjs


I would like to do a path fading effect that would make the path disappear by fading its stroke progressively along the path.

What I'm able to do for now is removing one by one each of the segments of the path, producing a rather poor effect: sketch.

var circle = new Path.Circle({
    center: view.center,
    radius: 50,
    strokeColor: 'black',
    closed: false
});
circle.addSegment(circle.firstSegment);

fade();

function fade() {
    if (circle.segments.length > 0) {
        setTimeout(function() {
            circle.lastSegment.remove();
            fade();
        }, 1000);
    }
}

Is there a way to make the animation smoother ?


Solution

  • To do a smooth path animation, you don't have to necessarily remove segments, you can also play with path.dashArray and path.dashOffset.
    By setting dash array to the length of the path and by animating dash offset, you can achieve what you are looking for.
    Look at this schema for better understanding:

    enter image description here

    Here is a sketch demonstrating the solution.

    enter image description here

    // create path
    var path = new Path.Circle({
        center: view.center,
        radius: 50,
        strokeColor: 'black',
        closed: false
    });
    path.addSegment(path.firstSegment);
    
    // set dash array as long as path length
    path.dashArray = [path.length, path.length];
    
    // on frame...
    function onFrame(event) {
        // ...increment dash offset
        path.dashOffset += 1;
    }