Reputation: 343
I am trying to animate a circle within a given set of points using canvas and request animation frame.
For that I have used a function like below:
function animloop(){
while(ny > pipeEnds.y) {
ctx.clearRect(0, 0, w, h);
drawCircle(nx, ny);
ny--;
nx = nx;
}
requestAnimFrame(animloop);
}
animloop();
function drawCircle(cx, cy){
ctx.beginPath();
ctx.arc(cx, cy, 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "black";
ctx.fill();
ctx.closePath();
}
The circle moves within the given set of points but the animation cant be seen. When the page loads the circle reaches the final position.
The code can be viewed in this fiddle.
Upvotes: 0
Views: 489
Reputation:
Just replace the while
with if
:
function animloop(){
if (ny > pipeEnds.y) {
...
What happens is that when you use while
you are creating an internal loop which won't finish until the criteria is fulfilled meaning the rAF won't be called until after this resulting in no visible movement as the "movement" is done at that point.
Using if
will check once, then call rAF and so on.
Hope this helps!
Upvotes: 1