0

I'm writing a script which changes the colours of a stick-man's arms and legs. Once "he" is selected, it effectively just mirrors the colours:

//Declare and initialize variables
var msgType = "";
var app;
var docRef = app.activeDocument;
var testColor = docRef.swatches.getByName("CMYK Green");
var leftColor = docRef.swatches.getByName("LeftColor");
var rightColor = docRef.swatches.getByName("RightColor");

function sameColor(CMYKColor1, CMYKColor2) {
    "use strict";
    var isTheSameColor;
    if ((CMYKColor1.cyan === CMYKColor2.cyan) && (CMYKColor1.magenta === CMYKColor2.magenta) && (CMYKColor1.yellow === CMYKColor2.yellow) && (CMYKColor1.black === CMYKColor2.black)) {
        isTheSameColor = true;
    } else {
        isTheSameColor = false;
    }
    return isTheSameColor;
}


// check if a document is open in Illustrator.
if (app.documents.length > 0) {
    var mySelection = app.activeDocument.selection;
    var index;
    // Loop through all selected objects
    for (index = 0; index < mySelection.length; index += 1) {
        // Switch left and right colours
        if (sameColor(mySelection[index].strokeColor, leftColor.color)) {
            mySelection[index].strokeColor = rightColor.color;
        }
        if (sameColor(mySelection[index].strokeColor, rightColor.color)) {
            mySelection[index].strokeColor = leftColor.color;
        }
        if (sameColor(mySelection[index].fillColor, leftColor.color)) {
            mySelection[index].fillColor = rightColor.color;
        }
        if (sameColor(mySelection[index].fillColor, rightColor.color)) {
            mySelection[index].fillColor = leftColor.color;
        }

    }
}

It works, but it only works once (i.e. I can't toggle the change again). If I undo the change and try again it works again. Why is this?

Evan
  • 2,400
  • 1
  • 18
  • 34
Ben
  • 4,281
  • 8
  • 62
  • 103

1 Answers1

2

After a lot of head-scratching / debugging it turns out that it was changing the CMYK values to be not quite the same (by a tiny fraction).

enter image description here

Changed the following:

if ((CMYKColor1.cyan === CMYKColor2.cyan) ...

to:

if ((Math.round(CMYKColor1.cyan) === Math.round(CMYKColor2.cyan)) ... 

and it works fine now.

Ben
  • 4,281
  • 8
  • 62
  • 103