I am posting my code using canvas here on SO but I am also creating a working sample on JSFiddle here.
StackOverflow test bedfunction drawGrid() {
var cnv = document.getElementById("cnv");
var gridOptions = {
minorLines: {
separation: 5,
color: '#00FF00'
},
majorLines: {
separation: 30,
color: '#FF0000'
}
};
drawGridLines(cnv, gridOptions.minorLines);
drawGridLines(cnv, gridOptions.majorLines);
return;
}
function drawGridLines(cnv, lineOptions) {
var iWidth = cnv.width;
var iHeight = cnv.height;
var ctx = cnv.getContext('2d');
ctx.strokeStyle = lineOptions.color;
ctx.strokeWidth = 1;
ctx.beginPath();
var iCount = null;
var i = null;
var x = null;
var y = null;
iCount = Math.floor(iWidth / lineOptions.separation);
for (i = 1; i <= iCount; i++) {
x = (i * lineOptions.separation);
ctx.moveTo(x, 0);
ctx.lineTo(x, iHeight);
ctx.stroke();
}
iCount = Math.floor(iHeight / lineOptions.separation);
for (i = 1; i <= iCount; i++) {
y = (i * lineOptions.separation);
ctx.moveTo(0, y);
ctx.lineTo(iWidth, y);
ctx.stroke();
}
ctx.closePath();
return;
}
Using the canvas approach you can make the grid size dynamic by changing the separation parameter.
However, if your grid size is going to be static I feel that maybe you don't need to draw the grid. Just for the sake of displaying a grid to the user you could use CSS to repeat a background image as demonstrated in the fiddle here. That will also be good on page performance.