Jump to content
Search Community

DrawSVG separate compound paths

swampthang test
Moderator Tag

Warning: Please note

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax. 

Recommended Posts

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?

See the Pen pEqWpg?editors=1010 by swampthang (@swampthang) on CodePen

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...