在 Javascript 上使用 rgb 颜色对数组进行排序

Sort array with rgb color on Javascript

我的 javascript 中有一个 rgb 颜色的数组。假设它看起来像这样:

  colors = ['(133,10,22)', '(33,33,33)', '(255,255,255)', '(1,1,1)'];

如何对这个数组进行排序,以便首先获得最亮的颜色,最后获得最暗的颜色?所以最后我的数组看起来像这样例如:

 colors = ['(255,255,255)', '(133,10,22)', '(33,33,33)', '(1,1,1)'];

是否有人需要使用任何特定的库,或者像 r+g+b 的最大和最浅的颜色? 提前致谢。

正如@Juhuna 所指出的,亮度不是通道的总和。

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();