Skip to content

Instantly share code, notes, and snippets.

@stevenocchipinti
Created January 30, 2019 23:47
Show Gist options
  • Save stevenocchipinti/eb78331dc83289b7b9e7fcad911ebf68 to your computer and use it in GitHub Desktop.
Save stevenocchipinti/eb78331dc83289b7b9e7fcad911ebf68 to your computer and use it in GitHub Desktop.
Generate a 20% brighter color for hover
// https://gist.github.com/mjackson/5311256
// http://xahlee.info/js/js_convert_decimal_hexadecimal.html
/**
* Converts an RGB color value to HSV. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and v in the set [0, 1].
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The HSV representation
*/
function rgbToHsv(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max == 0 ? 0 : d / max;
if (max == min) {
h = 0; // achromatic
} else {
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, s, v ];
}
/**
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes h, s, and v are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param Number h The hue
* @param Number s The saturation
* @param Number v The value
* @return Array The RGB representation
*/
function hsvToRgb(h, s, v) {
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return [ r * 255, g * 255, b * 255 ];
}
var rgbToHex = function (rgb) {
var hex = Number(rgb).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
};
function hover(input) {
const colorString = input.replace(/^\s*#?/, "")
const r = parseInt(colorString[0] + colorString[1], 16)
const g = parseInt(colorString[2] + colorString[3], 16)
const b = parseInt(colorString[4] + colorString[5], 16)
const [h, s, v] = rgbToHsv(r, g, b)
const [rh, gh, bh] = hsvToRgb(h, s, v-0.2)
return "#" + rgbToHex(rh) + rgbToHex(gh) + rgbToHex(33)
}
console.log("#e4002b => " + hover("#e4002b"))
// #e4002b => #b10021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment