KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: 4D SVG Dashed Lines - The Basics Part 2
PRODUCT: 4D | VERSION: 12 | PLATFORM: Mac & Win
Published On: May 12, 2011

Mastering dashed lines in SVG is similar to mastering Reverse Polish Notation: initially it makes no sense, but once understood it is really quite simple and straight forward. 4D SVG Dashed Lines - The Basics Part 1 helps to begin the understanding process. This Tech Tip expands on that.

To create a dashed line via SVG use the new (in 4D v12) 4D SVG Component command SVG_SET_STROKE_DASHARRAY. It is the "array" part that is initially hard to understand, and it is there that a picture is worth a thousand words.

There are a multitude of explanations to the SVG "stroke-dasharray" attribute on the internet. All of them do a poor job of explaining how it works in layman terms. One of the most confusing parts is just how many arguments are necessary to define the "array" that the SVG engine will use.

The bottom line is that the SVG engine always uses an even number of elements in the "stroke-dasharray." However, it is unnecessary to define an even number of elements when entering arguments into the SVG_SET_STROKE_DASHARRAY command.

The list of arguments should have an even number of entries, but if an odd number of entries are passed, SVG will repeat the list so the total number of entries is even. For instance, the following two calls produce the exact same result.

$Dom_SVG:=SVG_New

$Dom_line:=SVG_New_line ($Dom_SVG;0;20;200;20)
SVG_SET_STROKE_WIDTH ($Dom_line;10)
SVG_SET_STROKE_DASHARRAY ($Dom_line;20;20;20)
SVG_SET_STROKE_BRUSH ($Dom_line;"red")

$Dom_line:=SVG_New_line ($Dom_SVG;0;40;200;40)
SVG_SET_STROKE_WIDTH ($Dom_line;10)
SVG_SET_STROKE_DASHARRAY ($Dom_line;20;20;20;20;20;20)
SVG_SET_STROKE_BRUSH ($Dom_line;"blue")




Actually, the first example could be shortened to one argument, as shown below, and produce the same result.

$Dom_SVG:=SVG_New

$Dom_line:=SVG_New_line ($Dom_SVG;0;20;200;20)
SVG_SET_STROKE_WIDTH ($Dom_line;10)
SVG_SET_STROKE_DASHARRAY ($Dom_line;20)
SVG_SET_STROKE_BRUSH ($Dom_line;"red")


To further visualize what the SVG engine is doing internally, consider the following code:

$Dom_SVG:=SVG_New

$Dom_line:=SVG_New_line ($Dom_SVG;0;20;200;20)
SVG_SET_STROKE_WIDTH ($Dom_line;10)
SVG_SET_STROKE_DASHARRAY ($Dom_line;20;20;40)
SVG_SET_STROKE_BRUSH ($Dom_line;"red")


The code above starts a pattern of a 20px dash, a 20px space, followed by a 40px dash. When the SVG engine internally doubles the three values to six values, repeating the entered three and produces the dashed line shown below:



The dash pattern of 20,20,40 appears as expected in the first series of "dash-space-dash" that ends at the first vertical line. But look at the second series between the verticle lines, it is "space-dash-space" but still in the 20;20;40 measurements. That is the effect of the dash-array being internally doubled by the SVG engine.