Bobby
Bobby

Reputation: 145

javascript: Map a temperature to a particular HSL Hue value

My question is different from the question referred to by Jon P in this question question pointed to by Jon P and flagged above as being a question that has already been asked. That question was to display an entire gradient of temperatures. This question is to attach a single hue to a single temperature.

I need to display a single numeric temperature value in a color that maps the temperature to a certain hue in a range of hues on an hsl wheel. I need upper temperatures to show as very red (330 on the hsl wheel) and lower temperatures as very blue (270 on the hsl wheel).

After a bit of work at the suggest of Scott Sauyet in comment below, I solved my problem and it is posted below.

Upvotes: 0

Views: 1682

Answers (1)

Bobby
Bobby

Reputation: 145

Based on an answer by Alnitak, in this post question 16399677 to show a temperature gradient, I developed a function to map a single temperature to a particular hue in a user definable range on an hsl color wheel. enter image description here

html
<canvas width="300" height="40" id="c"> </canvas>

javascript
var c = document.getElementById('c');
var ctx = c.getContext('2d');
temp = 70; // at 70, getHue() returns a purple around the 300deg mark
var hue = getHue(temp);
ctx.fillStyle = 'hsl(' + [hue, '100%', '50%'] + ')';
ctx.fillRect(0, 0, 40, 40);

function getHue(nowTemp) {
  // following hsl wheel counterclockwise from 0
  // to go clockwise, make maxHsl and minHsl negative 
  // nowTemp = 70;
  var maxHsl = 380; // maxHsl maps to max temp (here: 20deg past 360)
  var minHsl = 170; //  minhsl maps to min temp counter clockwise
  var rngHsl = maxHsl - minHsl; // = 210

  var maxTemp = 115;
  var minTemp = -10;
  var rngTemp = maxTemp - minTemp; // 125
  var degCnt = maxTemp - nowTemp; // 0
  var hslsDeg = rngHsl / rngTemp;  //210 / 125 = 1.68 Hsl-degs to Temp-degs
  var returnHue = (360 - ((degCnt * hslsDeg) - (maxHsl - 360))); 
  return returnHue;  
}

Upvotes: 3

Related Questions