Sub topic 13
Automating flat setup with a script
This chapter assumes you can already build a flat by hand. That means you know the layer structure, the stroke weight hierarchy, mirroring a half outline and stitching lines from the earlier chapters. It also assumes you can read basic JavaScript: variables, arrays, loops and functions. You do not need to be a programmer. The goal is to turn the repeated first ten minutes of every flat into one script you run once.
Why script the setup
Every flat starts the same way. You open a document, create the same five layers in the same order, and set the same stroke weights. If you do this by hand across a 40-piece collection, the layer names drift ("Stitching", "stitches", "Stitch lines"), and the order changes between files. A pattern maker who opens your file then has to work out your structure before reading the drawing.
A script fixes this by making the structure a decision you make once. Illustrator runs scripts written in ExtendScript, an older dialect of JavaScript. Save the file with a .jsx extension and run it from File > Scripts > Other Script. You can also place it in Illustrator's Presets/Scripts folder, which makes it appear in the File > Scripts menu after a restart.
Scripts work best for the mechanical parts of a flat: layers, units, repeated geometry and consistent strokes. They are poor at design decisions such as where a seam should sit, so leave those to you.
What the scripting model looks like
Illustrator exposes its contents as a tree of objects. You reach nearly everything through app.
app.activeDocumentis the file you are working in.doc.layersis the list of layers, and each layer has its ownpathItems.- A
pathItemis one path. It has properties such asclosed,filled,stroked,strokeWidthandstrokeDashes. - Colors are objects too. For a black stroke you create an
RGBColorand set its channels.
Units in scripts are points, with 72 points to an inch. A Letter-size artboard is 612 × 792 pt. Keep this in mind when you write coordinates, because the numbers in the examples below only make sense in points.
Step 1: create the standard layers
The layer order matters. In Illustrator, doc.layers.add() puts the new layer at the top of the stack. So you must list layer names from the bottom of the stack to the top. The reference sketch (Croquis) belongs at the bottom, and annotations belong at the top where nothing can cover them.
The version below is safe to run more than once. It reuses a layer if it already exists, and it renames the default "Layer 1" instead of leaving an empty layer behind.
// ExtendScript for Illustrator (.jsx): create the standard flat layers
// Names are listed from the bottom of the stack to the top.
var LAYER_NAMES = ["Croquis", "Outline", "Stitching", "Details", "Annotations"];
var doc = app.documents.length > 0
? app.activeDocument
: app.documents.add(DocumentColorSpace.RGB, 612, 792);
function getOrAddLayer(d, name) {
try {
return d.layers.getByName(name);
} catch (e) {
var layer = d.layers.add();
layer.name = name;
return layer;
}
}
// A new document starts with one layer called "Layer 1". Reuse it as the bottom layer.
if (doc.layers.length === 1 && doc.layers[0].name === "Layer 1") {
doc.layers[0].name = LAYER_NAMES[0];
}
for (var i = 0; i < LAYER_NAMES.length; i++) {
getOrAddLayer(doc, LAYER_NAMES[i]);
}
// The reference sketch should not move while you trace over it.
doc.layers.getByName("Croquis").locked = true;getByName throws an error when the layer does not exist. That is why the function wraps it in try and catch. This is the normal ExtendScript way to test for existence.
Step 2: draw a half outline and mirror it
Hand-drawn symmetry depends on your eye. A script can make it exact. You define the points of one half, then reflect each x coordinate across the center axis with 2 * cx - x. If the center axis is at x = 300, a point at x = 400 reflects to x = 200, and a point at x = 380 reflects to x = 220. The y values stay the same.
The order of the mirrored points matters. The path has to continue around the shape without crossing itself. The half outline runs from the top center, down the right side, to the bottom center. The mirrored points must then run from the bottom up the left side. The loop below reads the half outline backward to produce exactly that order. It starts at the second-to-last point and stops before the first, because the first and last points sit on the axis and have no separate mirror image.
// ExtendScript for Illustrator (.jsx): draw a half outline, mirror it, and join it into one closed path
var doc = app.activeDocument;
var cx = 300; // x position of the center axis
var half = [[300, 700], [380, 700], [400, 650], [400, 300], [300, 300]];
var mirrored = [];
for (var i = half.length - 2; i >= 1; i--) {
mirrored.push([2 * cx - half[i][0], half[i][1]]);
}
var points = half.concat(mirrored);
var black = new RGBColor();
black.red = 0; black.green = 0; black.blue = 0;
var outline = doc.layers.getByName("Outline").pathItems.add();
outline.setEntirePath(points);
outline.closed = true;
outline.filled = false;
outline.stroked = true;
outline.strokeColor = black;
outline.strokeWidth = 1.5;This version draws on the Outline layer explicitly with doc.layers.getByName("Outline").pathItems.add(). If you call doc.pathItems.add() instead, Illustrator puts the path on whichever layer is currently active. That is often the wrong one.
The result has eight anchor points: the five from the half outline and three mirrored ones. Straight segments between them give a boxy shape. For a real garment you would add curve handles, but the principle is the same. You compute the mirrored position of every point and handle.
Step 3: add stitching on its own layer
Stitching sits on its own layer so you can hide, show or edit it without touching the outline. In the stroke hierarchy, stitching is thinner than the outline, so it reads as a detail. A dashed stroke represents the thread. Here the dashes are 3 pt long with 2 pt gaps.
// ExtendScript for Illustrator (.jsx): draw a dashed topstitch line on the Stitching layer
var doc = app.activeDocument;
var layer = doc.layers.getByName("Stitching");
var black = new RGBColor();
black.red = 0; black.green = 0; black.blue = 0;
var stitch = layer.pathItems.add();
stitch.setEntirePath([[310, 690], [390, 690]]);
stitch.filled = false;
stitch.stroked = true;
stitch.strokeColor = black;
stitch.strokeWidth = 0.5;
stitch.strokeDashes = [3, 2];strokeDashes takes an array that alternates dash length and gap length. An empty array [] gives a solid line. The stitch line here runs parallel to the top edge, 10 pt inside it. That offset is the same idea as a topstitch distance in construction.
Putting the three scripts together
You can run the scripts one after another, but a single file is easier to maintain. Put the shared values at the top, then call each step in order. Three habits make the file easier to reuse:
- Keep the layer names in one array so a rename happens in one place.
- Wrap repeated work in functions, for example one
makeBlack()function that returns theRGBColorinstead of building it three times. - Put the stroke weights in named variables such as
OUTLINE_WEIGHT = 1.5andSTITCH_WEIGHT = 0.5, so the hierarchy is visible at a glance.
When your studio changes a convention, for example moving topstitching from 0.5 pt to 0.75 pt, you edit one number and rerun the script on new files. Files that are already done stay as they are, which is usually what you want.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "There is no document" or an undefined error | No file is open and the script uses `app.activeDocument` | Check `app.documents.length` first, as in the layer script |
| "No such element" on `getByName` | The layer name is misspelled or the layers script has not run | Run the layer step first, and match the spelling and case exactly |
| Layers appear in the wrong order | The names were listed top to bottom | List names from bottom to top |
| Shape is a bow tie or crosses itself | Mirrored points were appended in the wrong order | Reverse the loop so the mirrored points run back up the other side |
| Path appears on the wrong layer | `doc.pathItems.add()` used the active layer | Call `add()` on the target layer's `pathItems` |
| Stitching is solid | `strokeDashes` was not set, or was set to `[]` | Assign a two-number array such as `[3, 2]` |
| Shape is far too small or large | Coordinates were treated as millimeters or inches | Remember that scripts use points |
Limits of scripting
Scripts are fast and exact, but they have limits you should know before you invest in them.
- A script does not know garment construction. It places points you give it. The design knowledge stays in your data.
- ExtendScript is an older engine. It does not support modern JavaScript features such as
let, arrow functions or template strings, so usevarand plain functions. - A bug in a script can create hundreds of objects in a second. Test on a copy of the file, and use Edit > Undo if the result is wrong.
- Scripts that rely on exact coordinates break when your artboard size or ruler origin changes. If you work with several sizes, compute positions from the artboard bounds rather than hardcoding them.
Exercise
A script adds the layers in the order "Annotations", "Details", "Stitching", "Outline", "Croquis" with doc.layers.add(). Where does the Croquis layer end up, and how do you change the script so the Croquis layer is at the bottom?
Show answer
Each add() places the new layer at the top, so Croquis, added last, ends up on top and would cover the drawing. Reverse the array to ["Croquis", "Outline", "Stitching", "Details", "Annotations"]. Then Croquis is added first and stays at the bottom, and Annotations is added last and sits on top.
Exercise
The half outline has the points [[300, 700], [380, 700], [400, 650], [400, 300], [300, 300]] and the center axis is at cx = 300. Which mirrored points does the loop produce, and in what order?
Show answer
The loop runs from index 3 down to index 1 and applies 2 * 300 - x. It produces [200, 300], then [200, 650], then [220, 700]. The first and last points are skipped because they lie on the axis. Joined to the original five points, the path closes back to [300, 700].
Exercise
You want the topstitch to look like a long dash with a short gap, 4 pt long and 1 pt apart. Which property do you set, and to what value? What do you set to make the line solid again?
Show answer
Set stitch.strokeDashes = [4, 1];. To make the line solid again, set stitch.strokeDashes = [];.