irie
irie

Reputation: 472

Draw Kinetic.Shape in for-loop - var i of for-loop isn't taken properly in drawFunc()

Is it possible to use the variable i of a for-loop (for(i=0; i<3; i++)) in wich the Kinetic.Shape is created to set the y-value in the custom drawFunc();

My code of the for-loop for the dynamic shape creation looks the following:

var layer = new Kinetic.Layer();

for (i = 0; i < 3; i++){
    layer.add(new Kinetic.Shape({
        x: 0,
        y: 0,
        width: 400,
        height: 400,
        drawFunc: function(canvas){
            console.log(i); //THIS LOG ALWAYS OUTPUTS THE MAX i-VALUE (here 3)
            var ctx = canvas.getContext();
            ctx.beginPath();
            ctx.fillStyle = 'black';
            ctx.fillRect(10, i*30+2, 200, 30);
            ctx.closePath();
            ctx.fill();
        }
    }));
}

stage.add(layer);

If i log the i-value in the custom drawFunc(); the result is always 3instead of 0, 1, 2, and because of that the ctx.fillRect draws all three shapes at y = 92.

Here is a fiddle of my code with the explained behaviour.

Am I missing something obvious? Any help is greatly appreciated.

Upvotes: 1

Views: 306

Answers (1)

Simon
Simon

Reputation: 6363

You can try something like this. By adding the layers using a function the value passed to the createLayer function is saved with each Kinetic.Shape object that's created through closures.

function createLayer(nbr){
    layer.add(new Kinetic.Shape({
        x: 0,
        y: 0,
        width: 400,
        height: 400,
        drawFunc: function(canvas){
            console.log(nbr);
            var ctx = canvas.getContext();
            ctx.beginPath();
            ctx.fillStyle = 'black';
            ctx.fillRect(10, nbr*30+2, 200, 30);
            ctx.closePath();
            ctx.fill();
        }
    }));
    }


for (var i = 0; i < 3; i++){
    createLayer(i);
}

Upvotes: 1

Related Questions