Search code examples
javascripthtmlcanvasfor-loopraster

HTML5 javascript: canvas context draw raster in for loop


Boy, I feel really stupid today. I just wanted to draw a raster (rows & columns) of different equally sized blocks on the HTML5 canvas. Something I though I've done many times before, but for some reason I cannot figure out the logic to get it to work!

To get an idea of where the blocks will be placed, I thought I'd started out drawing different rectangles in the raster. But the lines go beyond the 512x384 area I wanted to draw in on my 640x480 sized canvas. It's like the rectangles get drawn too big!

I am sure there is something really simply I'm overlooking, but I cannot see it!

context.fillStyle="black";
context.fillRect(0, 0, 640, 480);
for (var x = 0; x<512; x=x+16)
{
    for(var y = 0; y<384; y=y+24)
    {
        context.beginPath();
        context.rect(x,y,x+16,y+24);
        context.strokeStyle="green";
        context.stroke();
    }
}

Solution

  • Are you sure you want to do this part?

    context.rect(x,y,x+16,y+24);
    

    Or maybe you intended this:

    context.rect(x,y,16,24);