I am building a star visualisation engine, and need to interpolate values received from the API. The HSL colour stops are:
-.63, hsl: 228° 100% 80%,
.165, hsl: 224° 100% 90%,
.33, hsl: 240° 100% 98%,
.495, hsl: 64° 100% 92%,
.66, hsl: 52° 100% 82%,
.825, hsl: 28° 100% 66%,
2.057, hsl: 6° 95% 65%,
Each star will return a colour value between -.63 and 2.057, I need a function that takes that value and gets a colour along the spectrum comprised of the above stops.
I've had some previous help but cannot for the life of me figure this out, and haven't been able to find a concise tutorial or walkthrough of interpolating HSL values. The only way I can figure this out is via an external lib, but that seems a ridiculous solution for something relatively simple. Any help would be appreciated!
A straightforward linear interpolation function in HSB space:
For values lower than the minimum input it always will return the first, and for higher than the maximum, the last color set.
The returned value is an HSL array, which can be used immediately in CSS. If your environment needs RGB colors you can use an hsl-to-rgb conversion function, such as in this earlier SO question. Check what your output device expects for the RGB range: 0.0 to 1.0, 0 to 100, or 0 to 255.
Note that this function cannot be used for
hsb
in general. The problem is thehue
part: this wraps around at 360 (degrees), and so attempting to interpolate between350
and10
will make it return cyan (the value around 170) instead of red (the value at 0).Here is a jsfiddle, displaying the output for a range of numbers.