javascript - Interpolate HSL Colours -
i building star visualisation engine, , need interpolate values received api. 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 return colour value between -.63 , 2.057, need function takes value , gets colour along spectrum comprised of above stops.
i've had previous cannot life of me figure out, , haven't been able find concise tutorial or walkthrough of interpolating hsl values. way can figure out via external lib, seems ridiculous solution relatively simple. appreciated!
a straightforward linear interpolation function in hsb space:
function get_color_for(value) { var i, h,s,b,stops = [ [-0.63, [228, 100, 80]], [0.165, [224, 100, 90]], [0.33, [240, 100, 98]], [0.495, [64, 100, 92]], [0.66, [52, 100, 82]], [0.825, [28, 100, 66]], [2.057, [6, 95, 65]] ]; if (value <= stops[0][0]) return stops[0][1]; if (value >= stops[stops.length - 1][0]) return stops[stops.length - 1][1]; = 0; while (value > stops[i][0]) i++; value -= stops[i-1][0]; value /= (stops[i][0]-stops[i-1][0]); h = stops[i-1][1][0]+(stops[i][1][0]-stops[i-1][1][0])*value; s = stops[i-1][1][1]+(stops[i][1][1]-stops[i-1][1][1])*value; b = stops[i-1][1][2]+(stops[i][1][2]-stops[i-1][1][2])*value; return [h,s,b]; }
for values lower minimum input return first, , higher maximum, last color set.
the returned value hsl array, can used in css. if environment needs rgb colors can use hsl-to-rgb conversion function, such in this earlier question. check output device expects rgb range: 0.0 1.0, 0 100, or 0 255.
note function cannot used hsb
in general. problem hue
part: wraps around @ 360 (degrees), , attempting interpolate between 350
, 10
make return cyan (the value around 170) instead of red (the value @ 0).
here jsfiddle, displaying output range of numbers.
Comments
Post a Comment