【问题标题】:Sort array with rgb color on Javascript [duplicate]在Javascript上使用rgb颜色对数组进行排序[重复]
【发布时间】:2015-03-13 16:28:10
【问题描述】:

我的 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 的最大和最亮的颜色? 提前致谢。

【问题讨论】:

  • 对于一个非常简单的算法,它可以只是总和。每个数字代表每个通道中的光量,因此总共更多的光 = 更亮的颜色。
  • @pawel 所以 rgb(90, 90, 90) 比 rgb(255, 0, 0) 亮?

标签: javascript arrays sorting colors rgb


【解决方案1】:

正如@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();

【讨论】:

  • 亮度不是通道的总和。
  • tack 我用这个总和然后只是排序。而且我认为效果很好。
猜你喜欢
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2014-05-17
  • 2023-03-26
相关资源
最近更新 更多