Gradients are created by color interpolation between adjacent color stops. When we manually click on any point of the gradient slider, a stop with a location from 0 to 100 is added to it. Based on the location, Illustrator calculates the color and opacity of the new stop.
The gradient stops are an array of objects. The array is rebuilt when we move the stops in the Gradient panel. The
activeDocument.gradients[index].gradientStops.add() method adds a stop to the end of the array.
What you need to know when adding a stop:
- as the array is reindexed, the last stop of the old gradient becomes the penultimate in the array. The new one replaces it and gets its color, opacity;
- by default you cannot add a new color stop between the desired pairl;
- a new stop is always placed at the last position (100);
- if the new stop is at position 100 and the previous stop is at any position, then the old last one will move to the middle between them. We get an even distribution;
- if the last stop is not at the max position, it will remain in its place, and the new stop will be placed at 100. That is, there will not be an even distribution.
Knowing this behavior of color stops, let’s make a simple script that adds a stop at an equal distance between the last and the previous one. Keep in mind that the last one may not be on an edge, and there can be any number of stops in the gradient.
var gStops = selection.fillColor.gradient.gradientStops;
var beforeLastStop = gStops[gStops.length - 2];
var lastStop = gStops[gStops.length - 1];
var oldPos = lastStop.rampPoint;
var newStop = gStops.add();
lastStop.rampPoint = beforeLastStop.rampPoint + (oldPos - beforeLastStop.rampPoint) / 2;
gStops = selection.fillColor.gradient.gradientStops;
lastStop = gStops[gStops.length - 1];
lastStop.rampPoint = oldPos;
If you take the linear interpolation algorithms, you can make an advanced version of the demonstrated script that calculates a transient color and opacity value for the middle stop.