javascript:将温度映射到特定的 HSL 色调值

javascript: Map a temperature to a particular HSL Hue value

我的问题与 Jon P in this question question pointed to by Jon P 提到的问题不同,上面标记为已经提出的问题。这个问题是要显示整个温度梯度。这道题是将单一的色调附加到单一的温度上。

我需要以一种颜色显示单个数字温度值,该颜色将温度映射到 hsl 轮上一系列色调中的特定色调。我需要较高的温度显示为非常红色(hsl 轮上为 330),较低的温度显示为非常蓝(hsl 轮上为 270)。

根据下面评论中 Scott Sauyet 的建议进行了一些工作后,我解决了我的问题,并将其发布在下面。

基于 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.

的回答
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;  
}