Reputation: 225
I am able to animate the concentric circles on a canvas using FabricJs Canvas. I am able to make an infinite animation up to the last outer circle however the last outer remains on the canvas and my goal is to restart the animation from the inner circle up to the outer circle. Here is what i have tried.
const canvas = new fabric.Canvas('gameCanvas', {
selection: false
});
fabric.Object.prototype.originX = fabric.Object.prototype.originY = 'center';
let circles = [];
document.addEventListener('DOMContentLoaded', function() {
drawCircles();
});
document.getElementById('animateBtn').addEventListener('click', function()
{
canvas.clear();
animateCircles();//This function will trigger the animation
});
function makeCircle(r)
{
return new fabric.Circle({
left: 300,
top: 120,
strokeWidth: 1.5,
radius: r,
fill: 'white',
stroke: 'black',
selectable: false,
hoverCursor: 'default',
hasControls: false,
hasBorders: false
});
}
//This function would draw 10 concentric circles on the canvas
function drawCircles()
{
for(let i = 9; i >= 0; i--)
{
let circle = makeCircle(10*(i + 1));
circles.push(circle);
canvas.add(circle);
}
}
function animateCircles()
{
canvas.clear();
function loop(i)
{
if (i < 0) return;
circles[i].animate({
opacity: 1
}, {
duration: 500, //the animation last 5 ms
easing: fabric.util.ease['easeInElastic'],
onChange: canvas.renderAll.bind(canvas),
onComplete: function () {
circles[i].setCoords();
canvas.add(circles[i]);
canvas.renderAll();
loop(i - 1);
}
});
}
loop(9);
setInterval(function()
{
canvas.clear();
loop(9);
}, 5000); //Repeat the animation every 5 seconds
}
#container {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
}
#animateBtn {
margin-bottom: .5em;
}
<div id="container">
<button id="animateBtn">Start Animation</button>
<canvas id="gameCanvas" width="600" height="240" style="border: 2px solid green;"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.min.js"></script>
Upvotes: 1
Views: 333
Reputation: 2958
It's because you are calling setInterval()
every 5000ms and aso trying to animate the tenth circle at that same time. 500ms * 10 = 5000ms
. So right when the tenth circle goes to animate you are recalling the loop function by way of setInterval()
Change the recall time to 5500ms
setInterval(function () {
canvas.clear();
loop(9);
}, 5500); //Repeat the animation every 5 seconds
Upvotes: 1