Mobile app version of vmapp.org
Login or Join
Barnes313

: Script to automatically snap all points to grid in Adobe Illustrator? How would you write a script to move all points of all selected paths to the nearest (non-pixel grid) grid point? e.g.

@Barnes313

Posted in: #Cs6 #Grids #IllustratorScripting #Javascript

How would you write a script to move all points of all selected paths to the nearest (non-pixel grid) grid point?



e.g. I want all of the points of each polygon/path to snap to the nearest point on a custom grid. Mine is setup as 1 grid unit = 11.338px or 4mm, but ideally the script would extend to any unit value

MY PSEUDOCODE, v0.1:

// set grid units as pixels - in my case 11.338px = 8mm = 1 grid unit

units = 11.338


// Nested loop through all polygons/paths, then all points in each polygon

For each Polygon {

For each Point P in Polygon {

// move the Point x, y to the nearest grid point in units
P.x = units * Round(P.x/units)
P.y = units * Round(P.y/units)
}
}


Does this make sense? It's been a while since I've done any programming.
I've also never scripted for Illustrator, so not exactly sure how to implement this.

LINK: I've looked at the post by @KromStern but not sure how to implement based on that thread. How to align all selected points to a grid?

10.01% popularity Vote Up Vote Down


Login to follow query

More posts by @Barnes313

1 Comments

Sorted by latest first Latest Oldest Best

 

@Kimberly620

Here you go, make sure the paths that you want to snap are selected:

// jooSnapToDocumentGrid.jsx
#target illustrator

main();

function main(){
var grid = getDocumentGrid();
snapSelectedPathToDocumentGrid(activeDocument.selection, grid);
}

function snapSelectedPathToDocumentGrid(sel, grid){
for(var i = 0; i < sel.length; i++){
try {
var pp = sel[i].pathPoints;
for(var j = 0; j < pp.length; j++){
var p = pp[j];
p.leftDirection = nearestGrid(p.leftDirection, grid);
p.rightDirection = nearestGrid(p.rightDirection, grid);
p.anchor = nearestGrid(p.anchor, grid);
}
} catch(err) { }
}
}

function getDocumentGrid(){
var prf = app.preferences;
var ticks = prf.getIntegerPreference('Grid/Horizontal/Ticks');
var spacing = prf.getRealPreference('Grid/Horizontal/Spacing');
return spacing/ticks;
}

function nearestGrid(anchor, grid) {
return [Math.round(anchor[0] / grid) * grid,
Math.round(anchor[1] / grid) * grid ];
}

10% popularity Vote Up Vote Down


Back to top | Use Dark Theme