Skip to main content
Inspiring
November 16, 2022
Answered

Get spot colors from selected object / group objects

  • November 16, 2022
  • 5 replies
  • 4599 views

Hi community, hope you're doing awesome. Can anyone help me to modify this code?

 

Credits to @femkeblanco 

 

function WriteColours(myVariable){
var font = "Arial-BoldItalicMT";
var size = 20.02;//size font
if((myVariable == "Truck") || (myVariable == "Mini Van") || (myVariable == "Bus")){
var w = size * 2.3, h = size, x = 440, y = -73; // width, height, left and top
}
if((myVariable == "Civic") || (myVariable == "Corolla")){
var w = size * 2.3, h = size, x = 64, y = -628; // width, height, left and top
}
var doc = app.activeDocument;
var group = doc.groupItems.add();
for (var i = 2; i < doc.swatches.length; i++) {
var rect = doc.pathItems.rectangle(y, x, w, h);
var text = doc.textFrames.areaText(rect);
text.textRange.textFont = textFonts[font];
text.contents = doc.swatches[i].name + ",";
text.textRange.size = size;
while (text.lines[0].characters.length < text.characters.length) {
text.textPath.width += size;
}
x += text.textPath.width;
text.move(group, ElementPlacement.PLACEATEND);
}
}

 

I pass trough different options different parameter to write/draw the text boxes depending of what it comes to the function, position x and y changes depending on the option, but right now it generates the colors from the swatches in the document not form the selection, can anybody help me modifying this to get colors only from what i have selected? Thanks!

This topic has been closed for replies.
Correct answer m1b

@m1bfor this time I don't need the chips, I just need the code to write in a single text frame (or various) the colors (fill colors) in a selected object, like:

Red 186, Yellow 112, Black C.


Okay I see, like this?

(function () {

    // example usage:
    WriteColours4('Truck');

    // initial code courtesy @femkeblanco
    // modified by @AntonioPacheco
    // modified by @m1b
    function WriteColours4(myVariable) {

        var font = "Arial-BoldItalicMT";
        var size = 20.02; //size font

        if (myVariable == "Truck"
            || myVariable == "Mini Van"
            || myVariable == "Bus"
        ) {
            var w = size * 2.3,
                h = size,
                x = 440,
                y = -73; // width, height, left and top x = 385, y = -203
        }

        if (
            myVariable == "Civic"
            || myVariable == "Corolla"
        ) {
            var w = size * 2.3,
                h = size,
                x = 64,
                y = -628; // width, height, left and top x = 385, y = -203
        }

        var doc = app.activeDocument;
        var miColor = "";

        if (doc.selection.length == 0) {
            alert('Please make a selection and try again.');
            return;
        }


        // get colors from the selection

        var selectedSpotColors = [];

        for (var i = 0; i < doc.selection.length; i++) {

            var item = app.activeDocument.selection[i];
            var colorsOfSelectedItem = getBasicColorsFromItem(item);

            for (var c = 0; c < colorsOfSelectedItem.fillColors.length; c++) {

                var miColor = colorsOfSelectedItem.fillColors[c];

                if (miColor.typename == 'SpotColor')
                    selectedSpotColors.push(miColor);

            }

        }

        // now list the colors in a text frame
        var group = doc.groupItems.add(),
            colorNames = [],
            unique = {};

        for (var c = 0; c < selectedSpotColors.length; c++) {

            var colorName = selectedSpotColors[c].spot.name;

            // only add if unique
            if (unique[colorName] == undefined) {
                unique[colorName] = true;
                colorNames.push(colorName);
            }

        }

        // draw the text
        var text = doc.textFrames.pointText([x, y]);
        text.textRange.textFont = textFonts[font];
        text.contents = colorNames.join(', ');
        text.textRange.size = size;

    };


    /**
     * Returns array of swatches or colors
     * found in fill or stroke of page item.
     * @7111211 m1b
     * @version 2022-10-11
     * @9397041 {PageItem} item - an Illustrator page item.
     * @Returns {Object} -  {fillColors: Array<Color>, strokeColors: Array<Color>}
     */
    function getBasicColorsFromItem(item) {

        if (item == undefined)
            throw Error('getItemColor: No item supplied.');

        var noColor = "[NoColor]",
            colorables = [],
            foundColors = {
                fillColors: [],
                strokeColors: []
            };

        // collect all the colorables
        if (item.constructor.name == 'PathItem') {
            colorables.push(item);
        }

        else if (
            item.constructor.name == 'CompoundPathItem'
            && item.pathItems
        ) {
            colorables.push(item.pathItems[0]);
        }

        else if (
            item.constructor.name == 'TextFrame'
            && item.textRanges
        ) {
            for (var i = item.textRanges.length - 1; i >= 0; i--)
                colorables.push({
                    fillColor: item.textRanges[i].characterAttributes.fillColor,
                    strokeColor: item.textRanges[i].characterAttributes.strokeColor
                });
        }

        if (colorables.length > 0)

            for (var i = 0; i < colorables.length; i++) {

                if (
                    colorables[i].hasOwnProperty('fillColor')
                    && colorables[i].fillColor != noColor
                    && (
                        !colorables[i].hasOwnProperty('filled')
                        || colorables[i].filled == true
                    )
                    && colorables[i].fillColor != undefined
                )
                    foundColors.fillColors.push(colorables[i].fillColor);

                if (
                    colorables[i].hasOwnProperty('strokeColor')
                    && colorables[i].strokeColor != noColor
                    && (
                        colorables[i].constructor.name == 'CharacterAttributes'
                        || colorables[i].stroked == true
                    )
                    && colorables[i].strokeColor != undefined
                )
                    foundColors.strokeColors.push(colorables[i].strokeColor);

            }

        else if (item.constructor.name == 'GroupItem') {

            // add colors from grouped items

            for (var i = 0; i < item.pageItems.length; i++) {
                var found = getBasicColorsFromItem(item.pageItems[i]);
                foundColors.fillColors = foundColors.fillColors.concat(found.fillColors);
                foundColors.strokeColors = foundColors.strokeColors.concat(found.strokeColors);
            }

        }

        return foundColors;

    };

})();

5 replies

Inspiring
November 18, 2022

Update, I change the line from:

 

doc.selection[i].fillColor.spot.name;

 

To

 

pathItems[g].fillColor.spot.name;

 

And I added the cycle from above answers, it work but it only writes one color, like it is not entering the cycle or is finishing the cycle, not sure which variable to change or modify. Hope this helps too.

 

function WriteColours2(myVariable) {
var font = "Arial-BoldItalicMT";
var size = 20.02; //size font
if((myVariable == "Truck") || (myVariable == "Mini Van") || (myVariable == "Bus")){
var w = size * 2.3, h = size, x = 440, y = -73; // width, height, left and top x = 385, y = -203
}
if((myVariable == "Civic") || (myVariable == "Corolla")){
var w = size * 2.3, h = size, x = 64, y = -628; // width, height, left and top x = 385, y = -203
}
var doc = app.activeDocument;
var miColor = "";
if (doc.selection.length > 0) {
var group = doc.groupItems.add();
for (var i = 0; i < doc.selection.length; i++) {
var rect = doc.pathItems.rectangle(y, x, w, h);
var text = doc.textFrames.areaText(rect);
text.textRange.textFont = textFonts[font];
with (app.activeDocument.selection[0]) {
if (pathItems.length > 0)
{
for (var g = 0 ; g < pathItems.length; g++)
{
if (pathItems[g].filled == true)
{
miColor = pathItems[g].fillColor.spot.name;//Previously was doc.selection[i].fillColor.spot.name;
text.contents = miColor;
text.textRange.size = size;
while (text.lines[0].characters.length < text.characters.length) {
text.textPath.width += size;
}
x += text.textPath.width;
}
}
}
}
text.move(group, ElementPlacement.PLACEATEND);
}
}
}

m1b
Braniac
November 18, 2022

Hi @AntonioPacheco, I had a look at this for you. It was hard to work out what you were doing, and I changed quite a few things so that it made sense to me. For example, now I gather all the colors of the selection first, then I make the color chips. I have made a function that helps to gather the colors from a pageItem so I used that.

 

Did I understand your needs correctly?

- Mark

 

(function () {

    // example usage:
    WriteColours3('Truck');

    // initial code courtesy @femkeblanco
    // modified by @Antonio Pacheco HN
    // modified by @m1b
    function WriteColours3(myVariable) {
        
        var font = "Arial-BoldItalicMT";
        var size = 20.02; //size font

        if (myVariable == "Truck"
            || myVariable == "Mini Van"
            || myVariable == "Bus"
        ) {
            var w = size * 2.3,
                h = size,
                x = 440,
                y = -73; // width, height, left and top x = 385, y = -203
        }

        if (
            myVariable == "Civic"
            || myVariable == "Corolla"
        ) {
            var w = size * 2.3,
                h = size,
                x = 64,
                y = -628; // width, height, left and top x = 385, y = -203
        }

        var doc = app.activeDocument;
        var miColor = "";

        if (doc.selection.length == 0) {
            alert('Please make a selection and try again.');
            return;
        }


        // get colors from the selection

        var selectedSpotColors = [];

        for (var i = 0; i < doc.selection.length; i++) {

            var item = app.activeDocument.selection[i];
            var colorsOfSelectedItem = getBasicColorsFromItem(item);

            for (var c = 0; c < colorsOfSelectedItem.fillColors.length; c++) {

                var miColor = colorsOfSelectedItem.fillColors[c];

                if (miColor.typename == 'SpotColor')
                    selectedSpotColors.push(miColor);

            }

        }

        // now make color chips for each spot color found
        var group = doc.groupItems.add();

        for (var c = 0; c < selectedSpotColors.length; c++) {

            var miColor = selectedSpotColors[c];

            // draw the text
            var text = doc.textFrames.pointText([x, y]);
            text.textRange.textFont = textFonts[font];
            text.contents = miColor.spot.name;
            text.textRange.size = size;

            // draw rectangle around text
            var rect = doc.pathItems.rectangle(y + text.height, x, text.width, text.height);
            rect.fillColor = miColor;

            // advance x
            x += text.width;

            // group
            text.move(group, ElementPlacement.PLACEATEND);
            rect.move(group, ElementPlacement.PLACEATEND);

        }

    };


    /**
     * Returns array of swatches or colors
     * found in fill or stroke of page item.
     * @author m1b
     * @version 2022-10-11
     * @param {PageItem} item - an Illustrator page item.
     * @returns {Object} -  {fillColors: Array<Color>, strokeColors: Array<Color>}
     */
    function getBasicColorsFromItem(item) {

        if (item == undefined)
            throw Error('getItemColor: No item supplied.');

        var noColor = "[NoColor]",
            colorables = [],
            foundColors = {
                fillColors: [],
                strokeColors: []
            };

        // collect all the colorables
        if (item.constructor.name == 'PathItem') {
            colorables.push(item);
        }

        else if (
            item.constructor.name == 'CompoundPathItem'
            && item.pathItems
        ) {
            colorables.push(item.pathItems[0]);
        }

        else if (
            item.constructor.name == 'TextFrame'
            && item.textRanges
        ) {
            for (var i = item.textRanges.length - 1; i >= 0; i--)
                colorables.push({
                    fillColor: item.textRanges[i].characterAttributes.fillColor,
                    strokeColor: item.textRanges[i].characterAttributes.strokeColor
                });
        }

        if (colorables.length > 0)

            for (var i = 0; i < colorables.length; i++) {

                if (
                    colorables[i].hasOwnProperty('fillColor')
                    && colorables[i].fillColor != noColor
                    && (
                        !colorables[i].hasOwnProperty('filled')
                        || colorables[i].filled == true
                    )
                    && colorables[i].fillColor != undefined
                )
                    foundColors.fillColors.push(colorables[i].fillColor);

                if (
                    colorables[i].hasOwnProperty('strokeColor')
                    && colorables[i].strokeColor != noColor
                    && (
                        colorables[i].constructor.name == 'CharacterAttributes'
                        || colorables[i].stroked == true
                    )
                    && colorables[i].strokeColor != undefined
                )
                    foundColors.strokeColors.push(colorables[i].strokeColor);

            }

        else if (item.constructor.name == 'GroupItem') {

            // add colors from grouped items

            for (var i = 0; i < item.pageItems.length; i++) {
                var found = getBasicColorsFromItem(item.pageItems[i]);
                foundColors.fillColors = foundColors.fillColors.concat(found.fillColors);
                foundColors.strokeColors = foundColors.strokeColors.concat(found.strokeColors);
            }

        }

        return foundColors;

    };


})();

 

Inspiring
November 18, 2022

Ohh my...!! It's like my basic functions went to the gym and came back with more musles! Let me try it out.

Inspiring
November 18, 2022

Unfortunately nothing happened 😞

 

 

Inspiring
November 17, 2022

I found a way to show in alert the colors from a selection:

 

with (app.activeDocument.selection[0]) {
if (pathItems.length > 0)
{
alert(pathItems.length);
for (var g = 0 ; g < pathItems.length; g++)
{
if (pathItems[g].filled == true)
{
alert(pathItems[g].fillColor.spot.name);
}
}
}
} with (app.activeDocument.selection[0]) {
if (pathItems.length > 0)
{
alert(pathItems.length);
for (var g = 0 ; g < pathItems.length; g++)
{
if (pathItems[g].filled == true)
{
alert(pathItems[g].fillColor.spot.name);
}
}
}
}

Now I need to adapt it to the code, maybe somebody may find it useful

femkeblanco
Braniac
November 17, 2022
function WriteColours(myVariable) {
    var font = "Arial-BoldItalicMT";
    var size = 20.02;  //size font
    if ((myVariable == "Truck") || (myVariable == "Mini Van") || (myVariable == "Bus")) {
        var w = size * 2.3, h = size, x = 440, y = -73;  // width, height, left and top
    }
    if ((myVariable == "Civic") || (myVariable == "Corolla")) {
        var w = size * 2.3, h = size, x = 64, y = -628;  // width, height, left and top
    }
    var doc = app.activeDocument;
    if (doc.selection.length > 0) {
        var group = doc.groupItems.add();
        for (var i = 0; i < doc.selection.length; i++) {
            var rect = doc.pathItems.rectangle(y, x, w, h);
            var text = doc.textFrames.areaText(rect);
            text.textRange.textFont = textFonts[font];
            text.contents = doc.selection[i].fillColor.spot.name;
            text.textRange.size = size;
            while (text.lines[0].characters.length < text.characters.length) {
                text.textPath.width += size;
            }
            x += text.textPath.width;
            text.move(group, ElementPlacement.PLACEATEND);
        }
    }
}
WriteColours("Truck");
Inspiring
November 17, 2022

let me try it out later !

Inspiring
November 17, 2022

text.fillColor = app.activeDocument.selection[0].fillColor; //or text.strokeColor for strokes respectively

Inspiring
November 17, 2022

Thank you for your help! I still don't try this but it seems that it will color the text frame, what I would like to do is to set in text.contents the colors from the selection instead of getting the colors from the doc.swatches.

Inspiring
November 17, 2022

If you have the spot color in the selection[0].fillColor, then you get exactly spot. But if you want to get exactly just RGB color then you can get it by 

selection[0].fillColor.spot.color

Or maybe it will need to take for each channel (dont sure, cant test it now):

selection[0].fillColor.spot.color.blue //( , red, green)

 

If you work in ESTK then you can to see this properties in the Data Browser window (and if not, I really advise you to try it. When I discovered it, it opened up new horizons for me)

I usually create a variable to which I assign the necessary item and see what happens inside it

Charu Rajput
Braniac
November 17, 2022

Hi, 

Try following link if that can help.

https://productivista.com/make-a-list-of-colors-from-your-selection/

 

Best regards
Inspiring
November 17, 2022

thank you, kind of struggling already hehe if someone can help me with the code I provided I will appreciate it