Jimmery
Jimmery

Reputation: 10139

FabricJS: Repeating an animation with a delay

So I am using Fabric JS to animate a circle, like so:

                var clickedPulse = new fabric.Circle({
                    radius: 5,
                    fill: 'rgba(0,0,0,0)',
                    stroke: 'rgba(0,0,0,0.7)',
                    strokeWidth: 3,
                    left: options.e.layerX,
                    top: options.e.layerY,
                    selectable: false,
                    hasBorders: false,
                    hasControls: false,
                    originX: 'center',
                    originY: 'center'
                })
                canvas.add(clickedPulse);
                clickedPulse.animate({
                    radius: 100,
                    opacity: 0
                },{
                    onChange: canvas.renderAll.bind(canvas),
                    duration: 700,
                    onComplete: function() {
                        clickedPulse.remove();
                        canvas.renderAll();
                    }
                });

This works for me fine - it animates 1 circle, increasing its radius an decreasing its opacity until it finally disappears.

What I want: Is 3 circles, all doing the same animation, just each circle is delayed after each other - the end effect would be like 3 ripples moving out from a center point.

How best to achieve this using Fabric JS? I have considered just repeating the same animation but using setTimeout to delay it each time. Is there a better approach I can use?

Upvotes: 0

Views: 1477

Answers (1)

Observer
Observer

Reputation: 3706

setTimeout should be the best solution for your animation, but you can also check fiddle which is just changing duration and radius.

for (var i = 1; i < 4; i++){
    var clickedPulse = new fabric.Circle({
                    radius: 5,
                    fill: 'rgba(0,0,0,0)',
                    stroke: 'rgba(0,0,0,' + (1 - i / 4) + ')',
                    strokeWidth: 5,
                    left: 150,
                    top: 150,
                    selectable: false,
                    hasBorders: false,
                    hasControls: false,
                    originX: 'center',
                    originY: 'center'
                })
                canvas.add(clickedPulse);
                clickedPulse.animate({
                    radius: 100 - i*15,
                    opacity: 0
                },{
                    onChange: canvas.renderAll.bind(canvas),
                    duration: 600 + i*200,
                    onComplete: function() {
                        clickedPulse.remove();
                        canvas.renderAll();
                    }
                });
}

Upvotes: 1

Related Questions