我正在用javascript编写Adobe Illustrator脚本来填充选定颜色的对象。
我有32个物体和12个颜色样本。我想用每种颜色填充32个对象两次,然后用随机选择填充剩余的8个对象。我想以无法辨别的方式填充对象,因此只需循环遍历每个对象并为其指定下一个样本颜色就行不通。
这是我到目前为止所用的,但它并没有使用每种颜色至少两次并随意填充。
myObjects = app.activeDocument.selection;
myDocument = app.activeDocument;
if (myObjects instanceof Array) {
colourSwatches = myDocument.swatches.getSelected();
//if there are swatches
if (colourSwatches.length != 0) {
for (i = 0; i < myObjects.length; i++) {
//if the selection is a path or compound path
if (myObjects[i].typename == "PathItem" || myObjects[i].typename == "CompoundPathItem") {
selItem = myObjects[i];
selItem.filled = true;
//select colour from swatches at random and then fill
swatchIndex = Math.round( Math.random() * (colourSwatches.length - 1 ));
if (selItem.typename == "PathItem") {
selItem.fillColor = colourSwatches[swatchIndex].color;
} else {
selItem.pathItems[0].fillColor = colourSwatches[swatchIndex].color;
}
}
}
}
}
答案 0 :(得分:1)
不要随意挑选样本(这是你失控的地方),而是这样做:
即未经测试,但是这样的事情:
var targetArray = [];
// fill with the set of required colors, times 2
for (i=0; i < 12; i++)
{
targetArray[2*i] = i;
targetArray[2*i+1] = i;
}
// fill up to contain 32 items
for (i=24; i<32; i++)
targetArray[i] = Math.floor(Math.random() * colourSwatches.length);
(请参阅Getting random value from an array了解random
表达式。)
现在您有一个包含索引的数组,供要使用的样本。循环遍历你的对象并从数组中选择随机项,直到你完成(这将是好的)或你用完的项目(这表明你要填充的项目数不正确):
for (i = 0; i < myObjects.length; i++)
{
arrayIndex = Math.floor(Math.random() * targetArray.length);
swatchIndex = targetArray[arrayIndex];
targetArray.splice (arrayIndex,1);
selItem.fillColor = colourSwatches[swatchIndex].color;
}
答案 1 :(得分:0)
32个对象:
12种颜色:
var document = app.activeDocument;
var objects = document.selection; // 32 objects
var swatchColors = document.swatches.getSelected(); // 12 colors
var colors = swatchColors; // 12 colors
colors = colors.concat(swatchColors); // duplicate the 12 colors, 12*2 colors
// add 8 random colors
for (var i = 0; i < 8; i++) {
// create random index in [0, 11]
var randomIndex = Math.floor(Math.random() * swatchColors.length);
// add the random color to colors array
colors.push(swatchColors[randomIndex]);
// remove the added color from the swatches so no extra duplicates
swatchColors.splice(randomIndex, 1);
}
// now we have 32 objects and 32 colors
// in colors array, there are (12 * 2) + 8 random colors
for (var i = 0; i < objects.length; i++) {
objects[i].fillColor = colors[i].color;
}
执行后:
对象从上到下,从左到右迭代。这是document.selection
订单。因此,前24种颜色的应用顺序与样本相同。如果您想要随机订单,可以随机播放colors
。