lsaadev lsaadev - 20 days ago 6
Javascript Question

Grid offset by one

Ok, so I've been trying to get a grid to work on my canvas. Here's what I've got:

codepen link

for (var j = 0; j < rows; j++) {
for (var i = 0; i < cols; i++) {
var pix = new Pixel(i, j);
grid.push(pix);
}
}


Now, the problem is that on the grid array, the pixel on index 0 is actually the 2nd one and the last is the 1st. I want to change that but I can't see what the problem in the code is.

Answer

Take a look at your Pixel#draw() function:

this.draw = function () {
    rect(this.x, this.y, l, l);
    fill(0);
    stroke(20);
    if (this.on)
        fill(255);
}

Read this code line by line and really think about exactly what it's doing. Step through it with a piece of paper and a pencil to understand exactly what's going on.

Notice that you're calling the rect() function first, and then you're setting the fill and stroke.

This will cause each square to have the color of the previous cell. So it's not that your first Pixel is located in the second square, it's that the second Pixel is drawing itself based on the color of the first Pixel. The same is true for the first Pixel drawing itself based on the color of the last Pixel.

To fix your problem, just set the stroke and fill before you call the rect() function.

Side note: you also probably want to get into the habit of using { } curly brackets for every if statement, even one-liners like this:

if(this.one){
   fill(255);
}

This isn't causing any problems in your code yet, but it's a good habit to get into.