This is not as much a "having a problem with.." issue as it is a best practice question. Might even be an SVG gotcha.
The codepen shows attaching a drawing tool (like a pencil or whatever) to a drawSVG line drawing by using MorphSVGPlugin.pathDataToBezier and following drawSVG. Got it working pretty quickly but when I started testing a few SVGs, I ran into compound paths - where there were multiple M's in a single path creating separate visual lines.
When drawSVG runs by itself (with no visual pen image following along) it's not noticeable that compound move-to paths are drawing multiple lines in at the same time. But, when you're trying to make it look like a pen is drawing a line at a time it quickly falls apart visually.
So, I wrote a rather ugly function to check for and break apart compound paths and then replace them all.
function breakApartPaths(paths, svg) {
var sepPaths = [];
for ( let path of paths ) {
var pdata = path.getAttribute('d');
pdata = pdata.trim();
var subArr = pdata.split('M');
for ( let M of subArr ) {
if(M != "") {
var newPath = document.createElementNS("http://www.w3.org/2000/svg", 'path');
for ( var a = 0; a < path.attributes.length; a++ ) {
var N = path.attributes[a].name;
var V = path.attributes[a].value;
if(N != 'd') {
newPath.setAttributeNS('',N,V);
}
}
newPath.setAttributeNS('','d',`M${M}`);
sepPaths.push(newPath);
}
}
}
return sepPaths;
}
I get the sepPaths array, and then remove all the paths, replacing them with the new paths like this...
var paths = document.querySelectorAll(`${svgID} path`);
var newPaths = breakApartPaths(paths,$(svgID)[0]);
for( path of paths ) {
$(svgID)[0].removeChild(path);
}
for( path of newPaths ) {
$(svgID)[0].appendChild(path);
}
It works but feels a little dangerous. Anyone know a little safer, more DRY way to do this?