view raw
lsaadev lsaadev - 6 months ago 38
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);

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.


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

this.draw = function () {
    rect(this.x, this.y, l, l);
    if (this.on)

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:


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