Search code examples
javascriptpaperjs

subdividing paths in paper js


Working on a simple method to subdivide existing paths (or compoundPaths) in paper js. Does anyone have any advice, or know where I might be going wrong with this? My thinking was, I can take in a path, and the number of subdivisions to make ( subdivide(path,level) ), and then loop through that path, create new points at the midpoint, and then using these points, insert or cut into the original path.

function subdivide(path,level){
  var numPoints = path.index;
  var t_seg = [];

  for(var i = 0; i < level; i++){
     for(var j = 0; j < path.index*2; j+=2){
        var p_1 = j;
        var p_2 = j+1;

        var t_p = new Point((p_1.x+p_2.x)/2,(p_1.y+p_2.y)/2);
        t_seg.push(t_p);
     }
  }
  var t_path = new Path(t_seg);

  return t_path;
}

Any advice on this? There is a simplify method, but I would really just like to subdivide my existing paths...


Solution

  • You can use Path.flatten():

    // Create a circle shaped path at { x: 80, y: 50 }
    // with a radius of 35:
    var path = new Path.Circle({
        center: new Size(80, 50),
        radius: 35
    });
    
    // Select the path, so we can inspect its segments:
    path.selected = true;
    
    // Create a copy of the path and move it 150 points to the right:
    var copy = path.clone();
    copy.position.x += 150;
    
    // Convert its curves to points, with a max distance of 20:
    copy.flatten(20);
    

    (if I understood correctly)