Skip to content

Instantly share code, notes, and snippets.

@delfick

delfick/color.js Secret

Created September 11, 2020 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delfick/eda5c6b29748d41d16aedeac3d9796a5 to your computer and use it in GitHub Desktop.
Save delfick/eda5c6b29748d41d16aedeac3d9796a5 to your computer and use it in GitHub Desktop.
//From https://github.com/mattdesl/kelvin-to-rgb/blob/master/index.js
function kelvinToRGB (temp) {
let out = [0, 0, 0];
temp = temp / 100
let red, blue, green
if (temp <= 66) {
red = 255
} else {
red = temp - 60
red = 329.698727466 * Math.pow(red, -0.1332047592)
if (red < 0) {
red = 0
}
if (red > 255) {
red = 255
}
}
if (temp <= 66) {
green = temp
green = 99.4708025861 * Math.log(green) - 161.1195681661
if (green < 0) {
green = 0
}
if (green > 255) {
green = 255
}
} else {
green = temp - 60
green = 288.1221695283 * Math.pow(green, -0.0755148492)
if (green < 0) {
green = 0
}
if (green > 255) {
green = 255
}
}
if (temp >= 66) {
blue = 255
} else {
if (temp <= 19) {
blue = 0
} else {
blue = temp - 10
blue = 138.5177312231 * Math.log(blue) - 305.0447927307
if (blue < 0) {
blue = 0
}
if (blue > 255) {
blue = 255
}
}
}
out[0] = Math.floor(red)
out[1] = Math.floor(green)
out[2] = Math.floor(blue)
return out
}
//From https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion
function rgbToHsl(r, g, b){
r /= 255, g /= 255, b /= 255;
let max = Math.max(r, g, b), min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
let d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h * 360, s * 100, l * 100];
}
const colour = {
"Hue": hue,
"Saturation":100 * parseFloat(saturation),
"Brightness":100 * parseFloat(brightness),
"Kelvin":parseInt(kelvin)
};
if(colour.Saturation == 0) {
const rgb = kelvinToRGB(targetColor.Kelvin);
const hsl = rgbToHsl(rgb[0], rgb[1], rgb[2]);
colour.Hue = hsl[0]
colour.Saturation = 10 + ((Math.abs(colour.Kelvin - 7000) / 500) * 3)
}
const background_color = `hsl("${colour.Hue},${colour.Saturation}%,${colour.Brightness / 1.666}%")`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment