I want to find a way to get the length of the longest line segment in a SVG path. Since a path can jump from one point to another the getTotalLength()
command doesn't work. As a simple example look at the following path:
<path d="
M 0 0 L 100 0
M 0 10 L 50 10
M 0 20 L 150 20
">
While getTotalLength()
outputs 300
, I want 150
as my output.
Is there a way to accomplish this?
I found a way to solve the problem. It works by splitting the path in multiple segments and measuring the seperately:
function maxSectionLength(path){
let segments = path.attributes.d.value.split(/(?=[m,M])/),
testPath = document.createElementNS('http://www.w3.org/2000/svg',"path"),
max = 0;
for(let d of segments){
testPath.setAttributeNS(null, "d", d)
max = Math.max(max,testPath.getTotalLength());
}
return max;
}