Lucia
Lucia

Reputation: 13571

Why doesn't this For loop work in Canvas?

I was trying to get the canvas to display the i in a loop - I want the i to be changing just like the counting t, from 1-9 non-stop. I just couldn't figure out what's wrong. The javascript looks like this:

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||  
            window.webkitRequestAnimationFrame ||  
            window.mozRequestAnimationFrame    ||  
            window.oRequestAnimationFrame      ||  
            window.msRequestAnimationFrame     ||  
    function(callback){window.setTimeout(callback, 1000/60)}; 
})(); 

var cvs = document.getElementById("canvasId"),
    c = cvs.getContext("2d"),
    t = 0;

window.onload=function loop(){
    window.requestAnimFrame(loop);
    t++;

    for(i=0;i<10;i++){
        c.clearRect(0,0,cvs.width,cvs.height);
        c.font = "bold 90px Arial";
        c.fillText(i + " " + t, 100, 200);
    }
};

http://jsfiddle.net/luxiyalu/9UZU5/

This is part of a mini game and I've been stuck in here for 2 days; if anyone could tell me what's wrong with it... Thanks a lot!

Upvotes: 2

Views: 252

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

As you're iterating i from 0 to 9 in your drawing function, there is no time left between two drawings and the user can only see the last iteration value, that is 9.

I'm not sure of what you really want to achieve but it looks like you want this :

var cvs = document.getElementById("canvasId"),
    c = cvs.getContext("2d"),
    t = 0,
    i = 0;

window.onload = function loop(){
    window.requestAnimFrame(loop);
    i++;
    if (i==10) {
      i = 0;
      t++;
    }

    c.clearRect(0,0,cvs.width,cvs.height);
    c.font = "bold 90px Arial";
    c.fillText(i + " " + t, 100, 200);

};

Demonstration

Upvotes: 2

Related Questions