gka / chroma.js

JavaScript library for all kinds of color manipulations
https://gka.github.io/chroma.js/
Other
10.14k stars 546 forks source link

Alpha channel relative change #244

Open PhantomArt opened 4 years ago

PhantomArt commented 4 years ago

I run the following code:

console.log(chroma("rgba(255, 0, 255, 0.4)").set("rgba.a", "*0.5"));

Сonsole output: Uncaught Error: unknown format: 255,0,255,0.2,rgba

Am I doing something wrong?

johman10 commented 3 years ago

Hi! Found this issue while searching for something related.

I found that this works weirdly:

const parsedColor = chroma('#000000AB');
const newParsedColor = parsedColor.set("rgb.r", parsedColor.get("rgb.r") + 10);
console.log(newParsedColor.alpha() === parsedColor.alpha()) // false

It seems as if setting a color channel on color with an alpha set, doesn't actually return the alpha channel in the newly created color.

I guess a workaround could be to do:

const parsedColor = chroma('#000000AB');
const alpha = parsedColor.alpha();
const newParsedColor = parsedColor.set("rgb.r", parsedColor.get("rgb.r") + 10);
const newParsedColorWithAlpha = newParsedColor.alpha(alpha);
console.log(newParsedColorWithAlpha.alpha() === parsedColor.alpha()) // true

@PhantomArt in your case you might want to go with:

const color = chroma("rgba(255, 0, 255, 0.4)")
const newAlpha = color.alpha() * 0.5;
console.log(color.alpha(newAlpha));

However something really seems weird within this set method regarding alpha's. I think the origin is here: https://github.com/gka/chroma.js/blob/552048f0f0b64aed69b2a953569de24ea2f6e426/src/ops/set.js#L6, the method rgb will be called even though there is an alpha channel.

I think the best approach would be if this package starts considering rgba to be different from rgb because now it's half working and half not. It would make the API easier to understand and fix all above mentioned issues. :)