Javascript function that generates html colors according to value

Asked

Viewed 1,176 times

3

I need to create a Javascript function that takes an int and returns an html color code. The rule is: The smaller the number more "cold" is the generated color (light blue, for example) and the bigger the hotter. But the values should 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]

  • Face makes your function return the color code. Here a site where you can pick up some color codes as an example to see how much will be necessary to perform the gradient you want, Colors

1 answer

7


I created this basic function, which perhaps meets your need:

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 mixing percentage.

See working on JS Fiddle.


Simply put, 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, simply put the RGB values 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 on JS Fiddle.


Degraded:

It already runs a little outside the scope of the question, but it is worth mentioning the following: this function does the linear conversion in the RGB space. For the purpose of rainbow, and gradient with more varied colors, you can apply conversion in HSV or LAB space. What is a question more of mathematics than of JS, but it might be worth it if the design of the application behaves.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.