Canvas Grid

I needed a grid background for a canvas that would have transparency in it. Why not draw the grid on the fly and set it as the background of the canvas? I will cover drawing the grid in this post and setting it as the background in another. My script starts the same as any other script.

F=Math.floor; //Math functions

var canvas = document.getElementsByTagName('canvas')[0]; //get the first canvas element
var context = canvas.getContext('2d'); //canvas context
document.body.clientWidth; // fix bug in webkit: http://qfox.nl/weblog/218

Now that we have the basics I could play around with a drawing a grid. I wanted a grid based on squares. I knew I wanted gray squares with a white background and to be able to adjust the size easily.

context.fillStyle = "#FFF"; //background color - white
context.fillRect(0,0,canvas.width, canvas.height); //fill entire canvas

var q=10; //grid square height and width in pixels
a.fillStyle = "#CCCCCC"; //grid color - gray

Next I needed a loop through each column and row using the fillRect() method to draw each square. Here is the code before I turned it into one line.

for(j=Math.floor(canvas.height/q)+1; j>=0; j--) { //rows
    for(i=Math.floor(canvas.width/q)+1; i>=-1; i-=2) { //columns
        context.fillRect(i*q+j%2*q,j*q,q,q); 
        //argument x includes a offset based on row position
    }
}

And here is the one line, keep in mind that F=Math.floor

for(j=F(canvas.height/q)+1;j--;)for(i=F(canvas.width/q)+1;i>=-1;i-=2)context.fillRect(i*q+j%2*q,j*q,q,q);

To save bytes and make the code less readable, “var canvas” could be renamed to “var c” and “var context” to “var a”.

What It Looks Like


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *