I've read a lot in the very complete post: Formula to determine brightness of RGB color
What bothers me is that even with all those formulas, I can't get a fine result... And this is quite bothering since I want to sort colors in a palette, from darkest to lightest. If the sorting is wrong, it is quickly a lot of pain to watch.
Quick example with the formula: (0.2126*R + 0.7152*G + 0.0722*B) which seems to be the most common answer over the web.
Edited after Peter's answer
function colorCodeToRGB(colorCode) {
colorCode = colorCode.substr(1);
return [
colorCode.substr(0, 2),
colorCode.substr(2, 2),
colorCode.substr(4, 2)
].map(it => parseInt(it, 16));
}
const luminanceCoefficients = [.2126, .7152, .0722];
function getLuminance(color) {
const [r, g, b] = colorCodeToRGB(color);
return r * luminanceCoefficients[0] + g * luminanceCoefficients[1] + b * luminanceCoefficients[2];
}
function linearizeSRGB(colorChannel) {
colorChannel /= 255;
if (colorChannel <= .04045 ) {
return colorChannel / 12.92;
} else {
return Math.pow((colorChannel + .055)/1.055, 2.4);
}
}
console.log('First set of colors');
console.log('#1883b1', getLuminance('#1883b1'));
console.log('#2c3b4c', getLuminance('#2c3b4c'));
console.log('Second set of colors');
console.log('#920f1e', getLuminance('#920f1e'));
console.log('#c3313d', getLuminance('#c3313d'));
.c {
height: 2rem;
width: 2rem;
}
Sample of colors
<span class="c" style="background-color: #1883b1"> </span>
<span class="c" style="background-color: #2c3b4c"> </span>
<span class="c" style="background-color: #920f1e"> </span>
<span class="c" style="background-color: #c3313d"> </span>
Everyone can see that the first blue is lighter than the second one, and its value is smaller, although on the second set, the first red seems darker than the second one, although it has a smaller value...
I don't get it, is there some way to actually determine perceived brightness?
I've tested all of the formulas on the post mentioned at the beginning of this question, and by sliding the color picker, I always find funny cases that illustrate a problem. I've no constraints, I can work with HSL, RGB, CIELAB, whatever!
Thanks by advance guys!
rbg()
. Usehsl()
(Hue, Saturation, Luminosity). Scroll down to the HSL section in the linked page. – Scott Marcus