Traverse color gradient according to value

Asked

Viewed 746 times

0

I need to represent the temperature of a place using colors, the lowest temperature I should represent with blue, the intermediate with yellow and the highest with red.

But I can’t just fix these 3 colors, I would like to have a smoother transition between temperature changes, I want to go through a color gradient according to the value I assume

I want to paint a div according to what the temperature of that deposit is representing

30_____________________________________0_______________________________________-30 Gradiente de cor

1 answer

1


Let’s take as values range, 0 to 100 degrees Celsius.

100 degrees is the hottest, so it should appear red, RGB (255,0,0) Degree is the coldest, should appear blue, RGB (0.0.255)

So we calculated a coefficient, which is the ratio of 100 to 255. Dividing gives 2.55, that is, when the temperature is at 100 (maximum), we multiply by 2.55 to reach 255, the value of the maximum RGB. We now need to invert the values, when one increases, the other decreases. For this, we can add or subtract 255. I will directly calculate the Red value and invert the Blue value by subtracting 255.

To demonstrate, we will use a "range" type control and a bit of javascript to change the color as the control value changes:

$('#temp').on("change", function(){
  // como a faixa vai de 0 a 100, calcula o valor atual da cor:
  var coeficiente = 255/100; //2.55, ou seja, 100C corresponde a 255
  var temperatura = $(this).val();
  /*
   como 0 grau é o mais frio e 100 graus o mais quente,
   calcula o valor do red e o do blue no RGB
   Quente R=255, B=0
   Frio R=0, B=255
   
   Para chegar nesses valores, multiplicaos o coeficiente pelo valor da cor
   Como precisa inverter os valores (quando um for 0 o outro será 255),
   basta subtrair por 255 ou somar por 255
   Fiz o cálculo do azul subraindo 255, e como será negativo, multipliquei por -1
  */
  var red  =  (temperatura * coeficiente);
  var blue =  ((temperatura * coeficiente)-255)*-1;
  var cor = "rgb(" + red + ",0," + blue + ")";
  $('#temp-cor').css("background-color", cor);
})
#temp-cor {
  width: 100px;
  height: 20px;
  border: solid 1px #000;
  background-color: RGB(128,0,128);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span>Temperatura:</span>
  0<input id="temp" type="range" min="0" max="100" value="50">100
 
</div>
<div id="temp-cor"></div>

I made this example using only red and blue, but you can follow the same idea and calculate green and make the color spectrum brighter, but the idea is the same.

Browser other questions tagged

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