Sort array with rgb color on Javascript [duplicate]

╄→尐↘猪︶ㄣ 提交于 2020-01-03 04:24:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!