Adding grid lines using javascript

by Thomas

Grid lines have all sorts of uses.  They can help layout a site, be used as a decoration, or the background of a graph or chart.  The easiest way to make a grid is use a background image.  That’s simple enough, but a background image can’t easily be resized. That’s the advantage of drawing the grid in Javascript.

In order to draw the grid lines we’re going to use the css extensions, “-moz-element” and “-webkit-canvas”.  These extensions allow us to use a canvas as the background image of any element on the page.  The canvas allows us to draw anything we want, in this case, grid lines.

NOTE: this example only works in Firefox Chrome and Safari.

The easiest way to draw grid lines is to draw 2 lines and set the background to repeat.  What do I mean?

If you take this image of 2 lines and repeat it you get a grid.

If the top and left sides not being filled are a problem then you can add a border-top and border-left to the element to compensate.  Another solution is to add an offset to the background css of the grid width -1.  So if the grid is 32px by 32px you can add:

background-position: -31px -31px;

This will leave the right and bottom sides open however.  The most sensible for a graph or chart would

background-position: 0px -31px;

Assuming that you have your axes on the left and bottom.

 

Now to the code!