问题
I am having an array in my javascript with rgb colors. Let's say it looks like this:
colors = ['(133,10,22)', '(33,33,33)', '(255,255,255)', '(1,1,1)'];
How can I sort this array so as to get the lightest color first and the darkest last? So at the end my array to look like this for example:
colors = ['(255,255,255)', '(133,10,22)', '(33,33,33)', '(1,1,1)'];
Is there any particular library someone needs to use, or it is like the biggest sum of r+g+b the lightest the color? Thanks in advance.
回答1:
As @Juhuna pointed out, brightness is not the sum of the channels.
var colors = ['(133,10,22)', '(33,33,33)', '(255,255,255)', '(1,1,1)'];
function sumColor (str) {
var rgb = str.replace(/[()]/g, "").split(",").map(Number);
// Summing the channels does not calculate brightness, so this is incorrect:
// return rgb[0] + rgb[1] + rgb[2];
// To calculate relative luminance under sRGB and RGB colorspaces that use Rec. 709:
return 0.2126*rgb[0] + 0.7152*rgb[1] + 0.0722*rgb[2];
}
colors.sort(function (a, b) {
return sumColor(a) > sumColor(b);
}).reverse();
来源:https://stackoverflow.com/questions/27960722/sort-array-with-rgb-color-on-javascript