Search code examples
javascripthtmlcanvas

Why is my code not displaying boxes on the canvas further along the x after 8 on the y?


Im trying to create a 64 square checkerboard on the html canvas element in javascript. The problem is i cant seem to get the boxes to render plus 75 on the x axis (posX) after the first 8 have rendered on the y and i cant seem to understand what im doing wrong.

Here is the code i have been trying.

<body>
 
    <canvas id="mainCanvas" width="600" height="600"></canvas>
    <script src="js/main.js" ></script>
</body>

#mainCanvas {
  background-color: black; }


const canvas = document.getElementById("mainCanvas");
const ctx = canvas.getContext("2d");

const sWidth = 75;
const sHeight =75;
const sCount = 64;
let posY = 0;
let posX = 0;

function DrawSquare(posX,posY,color){
    console.log(`Drawing square at (${posX}, ${posY}) with color ${color}`);
    ctx.beginPath();
    ctx.rect(posX, posY, sWidth, sHeight);
    ctx.fillStyle = color;
    ctx.fill();
    ctx.closePath();
}

for(let i = 0;i < sCount;i++){

    if(i % 2  == 0){
    
        DrawSquare(posX, posY,"white");
        console.log("white"+posX)
     }else{
        DrawSquare(posX, posY,"black");
        console.log("black")
     }


     if(i>7){
        if(i%8==0){
            posX+=75;
         }
      }
     posY+=75;
}

Any help would be much appreciated and a thanks in advance.


Solution

  • As kikon noted, resetting the posY to 0 after every 8 squares is what you needed to do.

    However, if you're just drawing black and white squares, and you have a black background, you only need to draw 32 the white squares. After that, just detect when the column you're on is alternating from the start to know when to draw at posY = 0 vs posY = squareHeight (or in this case, 75px).

    const canvas = document.getElementById("mainCanvas");
    const ctx = canvas.getContext("2d");
    
    const squareWidth = 75;
    const squareHeight = 75;
    const squareCount = 32;
    let posY = 0;
    let posX = 0;
    
    function DrawSquare(posX, posY, color) {
      //console.log(`Drawing square at (${posX}, ${posY}) with color ${color}`);
      ctx.beginPath();
      ctx.rect(posX, posY, squareWidth, squareHeight);
      ctx.fillStyle = color;
      ctx.fill();
      ctx.closePath();
    }
    
    for (let i = 0; i <= squareCount; i++) {
      DrawSquare(posX, posY, "white");
    
      if (i > 0 && i % 4 == 0) {
        let isColumnEven = ((i / 4) % 2) == 0;
        if (isColumnEven) {
          posY = 0
        } else {
          posY = squareHeight
        }
        posX += squareWidth;
        continue;
      }
    
      // Move down a distance of 2 squareHeights
      // because you are skipping the black squares
      posY += squareHeight * 2;
    }
    #mainCanvas {
      background-color: black;
    }
    <body>
      <canvas id="mainCanvas" width="600" height="600"></canvas>
      <script src="js/main.js"></script>
    </body>