Skip to content

Instantly share code, notes, and snippets.

@jpfaraco
Created January 10, 2022 05:31
Show Gist options
  • Select an option

  • Save jpfaraco/88671cbe4c1774769d3648d49bb535c0 to your computer and use it in GitHub Desktop.

Select an option

Save jpfaraco/88671cbe4c1774769d3648d49bb535c0 to your computer and use it in GitHub Desktop.
Functions to convert color formats.
function RGBtoHSV(r, g, b) {
if (arguments.length === 1) {
g = r.g, b = r.b, r = r.r;
}
var max = Math.max(r, g, b), min = Math.min(r, g, b),
d = max - min,
h,
s = (max === 0 ? 0 : d / max),
v = max / 255;
switch (max) {
case min: h = 0; break;
case r: h = (g - b) + d * (g < b ? 6: 0); h /= 6 * d; break;
case g: h = (b - r) + d * 2; h /= 6 * d; break;
case b: h = (r - g) + d * 4; h /= 6 * d; break;
}
return [h*360,s,v];
}
function RGBtoHEX(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
function RGBtoLuminance(r, g, b) {
var a = [r, g, b].map(function (v) {
v /= 255;
return v <= 0.03928
? v / 12.92
: Math.pow( (v + 0.055) / 1.055, 2.4 );
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
function HEXtoRGB(hex) {
var rgb = hex.match(/[\d\w]{1,2}/g);
var rgbArray = [
Math.round(parseInt(rgb[0], 16)),
Math.round(parseInt(rgb[1], 16)),
Math.round(parseInt(rgb[2], 16))
];
return rgbArray;
}
function HSVtoRGB(h,s,v) {
let f= (n,k=(n+h/60)%6) => v - v*s*Math.max( Math.min(k,4-k,1), 0);
return [Math.round(f(5)*255),Math.round(f(3)*255),Math.round(f(1)*255)];
}
function HSVtoHEX(h,s,v) {
let rgb = HSVtoRGB(h,s,v);
let r = rgb[0];
let g = rgb[1];
let b = rgb[2];
return RGBtoHEX(r,g,b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment