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

Sort array with rgb color on Javascript

本文关键字:数组 排序 颜色 rgb Javascript      更新时间:2023-09-26

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