Skip to content

HEX to RGB And Sort

fabiantheblind edited this page Apr 15, 2016 · 1 revision
#includepath "~/Documents/;%USERPROFILE%Documents";
#include "basiljs/bundle/basil.js";
// this sketch shows:
//
// transformation from hex to rgb
// array of objects sorting
// adding additional data to an object

/**
 * Transform hex string to object
 * @param  {String} hexstr Hex string without #
 * @return {Array}        Array containing 3 values [RED, GREEN, BLUE]
 */
function rgbtohex(hexstr) {
  return [
  (parseInt(hexstr, 16) >> 16) & 0xff,
  (parseInt(hexstr, 16) >> 8) & 0xff,
    parseInt(hexstr, 16) & 0xff
  ];
}

/**
 * calculates a sum of 3 values in an array
 * @param  {Array} rgb holds [RED, GREEN, BLUE]
 * @return {Number} a sum of the RGB
 */
function combine(rgb) {
  return rgb[0] + rgb[1] + rgb[2];
}

/**
 * main function
 */
function draw() {
  // our basic object
  var obj = {
    colors: [{
      hex: '#123456'
    }, {
      hex: '#124567'
    }, {
      hex: '#537454'
    }]
  };
  // take a look at it
  b.println('basic json');
  b.println(obj);
  // data transformation
  for (var i = 0; i < obj.colors.length; i++) {
    var oneColor = obj.colors[i].hex; // isolate
    var rgb = rgbtohex(oneColor.slice(1));// hex to rgb
    obj.colors[i].rgb = rgb;// add to object
    obj.colors[i].rgbsum = combine(rgb);// calc a sum (brightest to darkest)
  }
  // now sort the array based on the sum
  obj.colors.sort(function(a, b) {
    var value1 = a.rgbsum;
    var value2 = b.rgbsum;
    if (value1 < value2) {
      return -1;
    }
    if (value1 > value2) {
      return 1;
    }
    return 0;
  });
  // take a look at the result
  b.println('updated json');
  b.println(obj);

  var rectWidth = b.width / obj.colors.length;// the width for the rectangles
  var x = 0;// x location. Will be updated in loop j
  // loop
  for (var j = 0; j < obj.colors.length; j++) {
    b.fill(obj.colors[j].rgb[0], obj.colors[j].rgb[1], obj.colors[j].rgb[2]); // set fill color
    b.rect(x, 0, rectWidth, b.height);// draw the rect
    x += rectWidth; // update x
  }
}// done
b.go(); // run it
Clone this wiki locally