You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现:将单个温度值映射到HSL色相值(非梯度展示)

Temperature to Single HSL Hue Mapping (JavaScript)

Hey there, I get that you need a direct 1:1 mapping from a single temperature value to an HSL hue—specifically higher temps showing up as that deep red around hue 330—unlike the duplicate question focused on full gradients, this is tailored for individual values. Let’s build this out step by step:

Key Setup First

First off, you’ll need to define a temperature range (min and max values) that your input temps fall within. This is non-negotiable because we need to scale the temperature to fit the hue spectrum. For example, let’s use 0°C (cool end) to 100°C (warm end) as a starting point—you can adjust these later to match your actual use case.

Reusable Mapping Function

Here’s a JavaScript function that handles the mapping, with flexibility to tweak colors and ranges:

function tempToHslHue(temperature, minTemp = 0, maxTemp = 100, coolHue = 240, warmHue = 330) {
  // Make sure the temp stays within our defined range (no weird hue values)
  const clampedTemp = Math.max(minTemp, Math.min(maxTemp, temperature));
  
  // Convert temp to a 0-1 normalized value (0 = min temp, 1 = max temp)
  const normalizedValue = (clampedTemp - minTemp) / (maxTemp - minTemp);
  
  // Map the normalized value to our desired hue range
  let hue;
  if (warmHue >= coolHue) {
    // Straight linear mapping (e.g., 240 blue → 330 deep red)
    hue = coolHue + normalizedValue * (warmHue - coolHue);
  } else {
    // Handle wrap-around on the color wheel (e.g., 270 purple → 30 orange-red)
    const totalRange = (360 - coolHue) + warmHue;
    hue = (coolHue + normalizedValue * totalRange) % 360;
  }
  
  // Return hue as a clean integer (HSL works with whole numbers too)
  return Math.round(hue);
}

How to Use It

Once you have the hue, you can create a full HSL color string (adjust saturation/lightness to your preference):

// Example: Get hue for 85°C
const currentTemp = 85;
const hue = tempToHslHue(currentTemp);
// Create a saturated, medium-brightness color
const tempColor = `hsl(${hue}, 80%, 50%)`;

// Use it in your UI—say, set a div's background
document.querySelector('.temp-indicator').style.backgroundColor = tempColor;

Customization Tips

  • Adjust the color range: Change coolHue to set the low-temp color (e.g., 180 for cyan, 210 for light blue). Keep warmHue at 330 for that deep red, or bump it to 350 for an even richer red.
  • Tweak temperature bounds: If you’re dealing with outdoor temps, set minTemp to -40 and maxTemp to 40 instead of 0-100.
  • Clamping safety: The function automatically clamps temps outside your range to the min/max hue, so you don’t have to worry about invalid inputs breaking things.

内容的提问来源于stack exchange,提问作者Bobby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:14:14