Skip to content

Instantly share code, notes, and snippets.

@jef-sure
Created June 24, 2022 06:53
Show Gist options
  • Save jef-sure/ec78a5b44b54853ceca372e7b5ac0888 to your computer and use it in GitHub Desktop.
Save jef-sure/ec78a5b44b54853ceca372e7b5ac0888 to your computer and use it in GitHub Desktop.
function clamp(rgb) {
return rgb < 0 ? 0 : rgb > 255 ? 255 : parseInt(rgb);
}
function weatherTempToRGB(temp) {
let r, g, b;
if (temp >= 23) {
let t = (temp - 23) / 27.0;
g = (1 - t) * 200;
r = 200 + t * 50;
b = 0;
} else {
let t = (23 - temp) / 33.0;
b = t * 200;
g = Math.sqrt((1 - t) >= 0 ? 1 - t : 0) * 200;
r = 220 - Math.sqrt(t / 2) * 200;
}
let mrgb = Math.max(clamp(r), clamp(g), clamp(b));
let cs = 224.0 / mrgb;
return [clamp(r * cs), clamp(g * cs), clamp(b * cs)];
}
function rgb(...values) {
return values.reduce((acc, cur) => {
let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);
return acc + (val.length === 1 ? '0' + val : val);
}, '').toUpperCase();
}
document.body.outerHTML = '<body style="display: flex; flex-flow: row wrap; height: auto"></body>';
for (let temp = -40; temp < 50; ++temp) {
let [r, g, b] = weatherTempToRGB(temp);
let tdiv = document.createElement('div');
tdiv.style.width = '7em';
tdiv.style.height = '2em';
tdiv.style.textAlign = 'center';
tdiv.style.backgroundColor = '#' + rgb(r, g, b);
tdiv.textContent = temp + ': ' + '#' + rgb(r, g, b);
document.body.appendChild(tdiv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment