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

时间:2015-01-15 09:50:48

标签: javascript arrays sorting colors rgb

我在我的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中最大的一样是最轻的颜色? 提前致谢。

1 个答案:

答案 0 :(得分:0)

正如@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();
相关问题