Javascript function that generates html colors according to value

Posted on

Question :

I need to create a Javascript function that takes an int and returns an html color code. The rule is: The smaller the number “cooler” is the color generated (light blue, for example) and the larger the warmer. However, the values must follow a gradient in such a way that the color generated for the number 1 is very similar, but different from the color generated for the number 2.

Assume that the values acceptable by the function are in the range [0, 100]


Answer :

I created this basic function, which might suit your needs:

function colorTween(c1,c2,p) {
  var r1 = parseInt(c1.substring(1,3),16);
  var g1 = parseInt(c1.substring(3,5),16);
  var b1 = parseInt(c1.substring(5,7),16);
  var r2 = parseInt(c2.substring(1,3),16);
  var g2 = parseInt(c2.substring(3,5),16);
  var b2 = parseInt(c2.substring(5,7),16);
  var r3 = (256+(r2-r1)*p/100+r1).toString(16);
  var g3 = (256+(g2-g1)*p/100+g1).toString(16);
  var b3 = (256+(b2-b1)*p/100+b1).toString(16);
  return '#'+r3.substring(1,3)+g3.substring(1,3)+b3.substring(1,3);

It can be optimized according to your specific need, but the syntax is basically in this format:

colorTween( '#000000', '#ffffff', 50 )

being the first parameter, the color equivalent to zero, the second, equivalent to 100, and the third, the desired percentage of mixing.

Watch working on JS Fiddle .

Simplifying, if colors are “fixed”:

function colorTween(p) {
  var r1 = 0xff;
  var g1 = 0x00;
  var b1 = 0x00;
  var r2 = 0xaa;
  var g2 = 0x33;
  var b2 = 0xfc;
  var r3 = (256+(r2-r1)*p/100+r1).toString(16);
  var g3 = (256+(g2-g1)*p/100+g1).toString(16);
  var b3 = (256+(b2-b1)*p/100+b1).toString(16);
  return '#'+r3.substring(1,3)+g3.substring(1,3)+b3.substring(1,3);

In this case, just put the values in RGB directly into the variables r1, g1, b1 and r2, g2, b2 respectively (or replace directly in the formula).

To use this version, simply provide the desired percentage in this format:

colorTween( 50 )

See working at JS Fiddle .

About gradients:

There is a little bit of the amplitude of the question, but the following is worth mentioning: this function converts linearly to RGB space. For rainbow effects, and gradients with more varied colors, conversion can be applied in the HSV or LAB space. This is a more mathematical question than JS, but it may be worth it if the application design supports it.


Leave a Reply

Your email address will not be published. Required fields are marked *