Wednesday, December 5, 2018

Generating Complementary Color Pairs with JavaScript

When using a library, such as Chart.js, you will sometimes want to assign colors to elementt, such as bars or pie wedges, in a functional way so that n items have unique colors.  Chart.js in particular allows you to provide a fill and a border color, each as an array in length equal to your dataset.

For the purpose of creating pleasant colors with "half tone" complements I recently rolled a few helper functions based on an example for generating random rgba color strings.  I hope they are useful to you.

 // biased towards the upper end of the brightness spectrum 
 function random_rgba() {
           var o = Math.round, r = Math.random, s = 100;
           var rgba = [];     
           rgba.push(o(r()*s)+155);
           rgba.push(o(r()*s)+155);
           rgba.push(o(r()*s)+155);
           rgba.push(1);
           return rgba;
       }
      
       function dimRGBA(rgba){
              var tone = .7;
              var dimtone = [];
              dimtone.push(Math.abs(rgba[0] * tone));
              dimtone.push(Math.abs(rgba[1] * tone));
              dimtone.push(Math.abs(rgba[2] * tone));
              dimtone.push(1);
              return dimtone;
       }
      
       function stringifyRgba(rgba){
              return 'rgba(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ',' + rgba[3] + ')';
       }
      
       function rgbaComplementaryPair(){
              var pair = [];
              var sourcecolor = random_rgba();
              var complement = dimRGBA(sourcecolor);
              pair.push(stringifyRgba(sourcecolor));
              pair.push(stringifyRgba(complement));
              return pair;
       }