KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: SVG Technique: Two ways of drawing a grid background
PRODUCT: 4D | VERSION: 12 | PLATFORM: Mac & Win
Published On: June 29, 2011

When the occasion arises for including a grid background to an SVG image, such as in a chart or graph, there are two techniques for accomplishing the task.

The first, and most obviouse, technique is to draw the grid with a series of horizontal and vertical lines as show in the first image and code snippet below. The demo is to draw a 20x20 px grid.



$X_L:=0
$Y_L:=0
$X2_L:=200
$Y2_L:=100

For ($Ndx;0;10)
    SVG_New_line ($SVG_T;$X_L+($Ndx*20);$Y_L;$X_L+($Ndx*20);$Y2_L;"blue";0.5)
    SVG_New_line ($SVG_T;$X_L;$Y_L+($Ndx*20);$X2_L;$Y_L+($Ndx*20);"blue";0.5)
End for


The second technique is to use the power of SVG patterns.

It starts with defining a pattern that will repeat 20x20 px rectangles and then associate a containing rectangle for the pattern. The fine point here is that this is a define and not a rendering element in the SVG document.

The final step is to use the pattern in a rectangle of the desired size. The image and snippet below demonstrate this technique.



$MyPat_T:=SVG_Define_pattern ($SVG_T;"myGrid";20;20;0;0;"userSpaceOnUse")
SVG_New_rect ($MyPat_T;0;0;20;20;0;0;"blue";"none";0.3)

SVG_New_rect ($SVG_T;0;0;200;100;0;0;"";"url(#myGrid)";0.3)


The advantage of the second technique is that regardless of the size of the render rectangle the grid pattern will be from edge to edge. In the first technique the lines will have to be adjusted for length with a different size if desired.