For-looping a canvas animation

I was wondering if it was possible in a not to complicated way to make this a for loop?

Im using code exactly like this for 9 different colours... a for-loop would shorten my code a lot. I'm just so new to JS, I can't really think of a way that is SIMPLE. The only thing that changes is "Red" to "Green" or "Yellow" and more. The colour name is the only change and the 'x' and 'y' coordinates.

 } else if (collides(myRectRed, x, y)) {
        context.fillStyle = "White";
        context.fillRect(107, 7, 90, 110);

        function callbackRed() {
            setTimeout(function returnSizeRed() {
                context.fillStyle = "Red";
                context.fillRect(107, 7, 90, 110);
            },50);
        }
        function callMIDRed(){
            setTimeout(function displayMidRed(){
                context.fillStyle = "Red";
                context.fillRect(119, 22, 60, 80);
                return callbackRed();
            },50);
        }
        setTimeout(function displayRectRed() {
            context.fillStyle = "Red";
            context.fillRect(139, 42, 20, 40);
            return callMIDRed();
        },50);

Upvotes: 0

Views: 75

Answers (2)

Danon
Danon

Reputation: 2973

Are you sure you need 3 Timeout Functions?

function first() {
    // something
    setTimeout(first, 50);
}
function second() {
    // something
    setTimeout(second, 50);
}
function third() {
    // something
    setTimeout(third, 50);
}

Maybe change the previous to this

function first() {
    // something
}
function second() {
    // something
}
function third() {
    // something
}

function invoke() {
    first();
    second();
    third();
    setTimeout(invoke, 50);
}

But i don't know, do what you want :D

Upvotes: 0

Danon
Danon

Reputation: 2973

Just keep important information in an array of objects. One object can contain Color, x, y. Let's say you have 3 of those objects in array.

Then, everytime this function invokes, you incremeant i by one, and if it reaches 3, you % it bring it back to 0, and again and again...

When you run function, you just take information from this array.

var s = [
 {color: "Red",   x: 120, y:120},
 {color: "Green", x: 160, y:120},
 {color: "Blue",  x: 200, y:120},
];

var i = 0;

var changeColors = function () {
  context.fillStyle = s[i].color;
  context.fillRect(s[i].x, s[i].y, 10, 10);
  i = i++ % 3;
}

And now, just set interval to this function (remember not to put () after function name in SetInterval function)

var interval = setInterval(changeColors, 1000);

Or to stop it

clearInterval(interval);

Upvotes: 1

Related Questions