1

There are 2 loops in which each one has different results, and with those loops, the axes (x, y) of the canvas boxes are specified. But at the time of entering the parameters, I am not clear about how to organize the loops with the canvas path, or a way in which it is executed properly according to the for.

bucle de eje x = for (var i = 9; i <= 19; i++) {
                    x = 50*i;
                  }

bucle de eje y = for (var i = 10; i >= 1; i--) {
                y = 50*i;
                }

function funcDelRect(){
        
    // for eje x 
        for (var i = 9; i <= 19; i++) {
            x = 50*i;
            console.log("1: " + x);
        
            console.log('--------------------');

        // for eje y 
        for (var i = 10; i >= 0; i--) {
                y = 50*i;
                console.log("2: " + y);

      // Canvas Rect();
            var canvas = document.getElementById('canvasGEO');
            var ctx = canvas.getContext("2d");

            ctx.beginPath();
            ctx.rect(x, y, 25, 25); 
            ctx.fillStyle = "gold";
            ctx.fill();
            ctx.stroke();
            ctx.closePath();
            }
        }   
    }
<canvas style="background-color: lightgreen; border: 1px solid black" id="canvasGEO" width="1000" height="700"></canvas>

    <button type="submit" id="agreeRect" onclick="funcDelRect()">Subir cuadros</button>

1 Answer 1

1

You are using the same variable to count the inner loop that counts the outer loop.

The result is that the outer loop will loop around with i set to the value -1, and thus will never exit

for (var i = 9; i <= 19; i++) {  // Using i = 9
    for (var i = 10; i >= 0; i--) { // using i again starts at 10
    }
    // i is now === -1
} // outer loop adds one to i so it is now 0 but will never exit i > 19

Either use two separate variables

var i,j;
for (i = 9; i <= 19; i++) { 
    for (j = 10; j >= 0; j--) {
    }
}

Or use locally scoped variables

for (let i = 9; i <= 19; i++) { 
    for (let i = 10; i >= 0; i--) {  // this i is scoped to this loop and is not
                                     // the same variable as the outer i
        // NOTE you can not access the outer i
    }
}

Hoisting

When you use var to declare variables always put them at the top of the function (Hoist them) to avoid errors like this.

Declaration types and scope.

For more on scope and variable declarations let, var and const

Sign up to request clarification or add additional context in comments.

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.