(Part 1 : Set stroke-dasharray & stroke-dashoffset in Percentage) – SVG Path

SVG Path
Set stroke-dasharray & stroke-dashoffset of SVG Path in % using JavaScript.

Get the total length of the Path

First create a SVG on which we will do experiments :

String shaped SVG

Get total length :

You can check the length with alert(totalLen);. We will do same thing using class (using function) and use this class in later sections :

Now we can check length with alert(SVGRoadInstance.pathLength);.

Set stroke-dasharray in % with single value

Define a method for setting stroke-dasharray :

Now set the stroke-dasharray


Another example :


Set stroke-dasharray in % with multiple values

Modify our method for setting stroke-dasharray :

Set stroke-dasharray :

setStrokeDasharrayInPercent(40, 10)

Another example :

setStrokeDasharrayInPercent(40, 5, 10, 5)

Set stroke-dashoffset in %

Add method for setting stroke-dashoffset :

Set stroke-dashoffset :

setStrokeDasharrayInPercent(25) & setStrokeDashoffsetInPercent(25)

Another exanple :

setStrokeDasharrayInPercent(50) & setStrokeDashoffsetInPercent(-25)

Whole code with an example :

setStrokeDasharrayInPercent(40, 5, 10, 5) & setStrokeDashoffsetInPercent(40)

Code is also available here. Useful links :