Search code examples
adobe-illustratorextendscript

How do I programmatically capture and replicate Ai path shape?


I'm using ExtendScript for scripting Adobe Illustrator. I was wondering if there was a sneaky way or a script available to programmatically capture and then replicate a path shape, sort of JavaScript's .toSource() equivalent.

Thanks


Solution

  • Try this:

    main();
    function main(){
    
    var doc = app.activeDocument; // get the active doc
    
    var coords = new Array(); // make a new array for the coords of the path
    var directions = new Array();
    
    var sel = doc.selection[0];// get first object in selection
    
    if(sel == null) {
        // check if something is slected
        alert ("You need to sevlect a path");
        return;
        }
    
        var points = sel.pathPoints;// isolate pathpoints
        // loop points
        for (var i = 0; i < points.length; i++) {
        // this could be done in one lines
        // just to see whats going on line like
    //~      coords.push(new Array(points[i].anchor[0],points[i].anchor[1]));
        var p = points[i]; // the point
        var a = p.anchor; // his anchor
        var px = a[0];// x
        var py = a[1]; // y
        var ldir = p.leftDirection;
        var rdir = p.rightDirection;
        directions.push(new Array(ldir,rdir));
        coords.push(new Array(px,py));// push into new array of array   
      }
    var new_path = doc.pathItems.add(); // add a new pathitem
    
    new_path.setEntirePath(coords);// now build the path
    
    
        // check if path was closed
    if(sel.closed){
        new_path.closed = true;
        }
    
    // set the left and right directions
    for(var j = 0; j < new_path.pathPoints.length;j++){
    
        new_path.pathPoints[j].leftDirection = directions[j][0];
        new_path.pathPoints[j].rightDirection = directions[j][1];    
        }
    }