So I am using asArray() to create rgba color from color provided as a string. I noticed a very strange behaviour when I create two colors from same orginal string. It seems like they both reference same object.

Take a look at this:

const color = 'red';

const fillColor = asArray(color);
const strokeColor = asArray(color);

fillColor[3] = 0.05;
strokeColor[3] = 0.2;


Expected output:

[255, 0, 0, 0.05]
[255, 0, 0, 0.2]

Actual output:

[255, 0, 0, 0.2]
[255, 0, 0, 0.2]

So it seems these colors are somehow bound and changing one changes another. What I tried is to deep copy a string like this:

const fillColor = asArray(color.repeat(1));
const strokeColor = asArray(color.repeat(1));

But it still acts the same.

How do I create different colors?

1 Answer 1


If you check the the openlayers documentation for the asArray function, it says that the results get cached. So your two results are indeed referring to the same object and should not be edited.

If you want to edit the colors afterwards, I would do something like:

const fillColor = JSON.parse(JSON.stringify(asArray(color)));
const strokeColor = JSON.parse(JSON.stringify(asArray(color));

fillColor[3] = 0.05;
strokeColor[3] = 0.2;

Which should solve your problem.

  • 2
    Simpler would be const fillColor = asArray(color).slice().
    – TomazicM
    Jul 26, 2022 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.