0

I'm making a canvas game in JavaScript and have some trouble saving the data. I'm placing images on the canvas with a for-loop and I want to save information for each image in objects. For each image an object.

function CreateBlocks(){
    for(var i = 0; i <= blocks; i++){
        var img   = new Image();
        img.src   = "/images/Block.png";

        blockObject = {
            x:    x, 
            y:    y, 
            points:  10
         }
         ctx.drawImage(img,x,y);

         x += 100;
         y += 100;
    }
}

Now this obviously overwrites the blockObject everytime it loops. I tried adding to loop value to the name of the object like block[i]Object or blockObject[i] but that returns syntax errors.

I could just create a single dimension array for each value, but that seems rather messy to me. How can I create the objects in the loop?

2 Answers 2

6

Simply use an array and push the new object each time:

function CreateBlocks(){
    var arr = [];

    for(var i = 0; i <= blocks; i++){
        var img   = new Image();
        img.src   = "/images/Block.png";

        arr.push({
            x:    x, 
            y:    y, 
            points:  10
         });

         ctx.drawImage(img,x,y);

         x += 100;
         y += 100;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you create a blockObjects array, your second idea, using the blockObject[i] syntax will work:

var blockObjects=[];

function CreateBlocks(){
    for(var i = 0; i <= blocks; i++){
        var img   = new Image();
        img.src   = "/images/Block.png";

        blockObjects[i] = {
            x:    x, 
            y:    y, 
            points:  10
        };
        ctx.drawImage(img,x,y);

        x += 100;
        y += 100;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.