Set background color based on outdoor temperature

Flo Schild picture Flo Schild · May 6, 2013 · Viewed 9.5k times · Source

Heyoh SO,

I have a temperature widget to implement on a project I am working on. Nothing is specially difficult, I've got a free API to retrieve the datas that I need ect.

BUT, the lovely designer who works with me would have a color feature for which I've got no good idea to start with...

He would to define a background-color depending on the current weather temperature.

Temperature color schema

I mean if the temperature is cold, like -20, the background color should be blue / violet / any cold color; and when it's warm, like 25, it should have a hot background-color like orange / red.

I think I could easily work with an array of "temperature steps", but I would prefer to work with a function that could define the color depending of the temperature. I know it's strange, I don't know if there is an algorithm to define a color by it's temperature color... This article is helpfull http://en.wikipedia.org/wiki/Color_temperature but quite complicated, if someone has any idea, even for a beginning, I am very interested !

I saw this thread: Display temperature as a color with C#?

But I'm not using C# and I don't want to, so if there is a solution in JavaScript, it would be perfect. I can eventually work with PHP or NodeJS if there is a server-side need.

EDIT - Answer:

Finally, I didn't have the choice to use a real colors gradient array, because of the graphic needs. But I still had to mix the colors of the closest steps depending of the temperature ! I wrote a small JS library to do that, that you will be able to find on GitHub soon, I'll post the link here.

You can find it here:

The presentation website of the project

Or the github project

Answer

Alnitak picture Alnitak · May 9, 2013

Your colour range looks to be the same as a "hue-only" sweep in "HSL colour space" from 270º (violetish) at -30ºC down to 30º (orange) at +30ºC

var hue = 30 + 240 * (30 - t) / 60;

If t is out of range, either clamp it before calling the above expression, or clamp h to the desired hue range afterwards.

On supported browsers you can use an hsl(h, s, l) colour string, or use commonly available "HSL to RGB" functions to convert the HSL colour into RGB.

See http://jsfiddle.net/V5HyL/