Skip to content

Instantly share code, notes, and snippets.

@vivekvasani
Created July 27, 2020 19:34
Show Gist options
  • Save vivekvasani/6d6a7c31e0beb0f3a3b341e66056a774 to your computer and use it in GitHub Desktop.
Save vivekvasani/6d6a7c31e0beb0f3a3b341e66056a774 to your computer and use it in GitHub Desktop.
function hexToRgb(hex) {
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function (m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function luminance(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;
}
const color1rgb = hexToRgb('#ffffff');
const color2rgb = hexToRgb('#B30000');
const color1luminance = luminance(color1rgb.r, color1rgb.g, color1rgb.b);
const color2luminance = luminance(color2rgb.r, color2rgb.g, color2rgb.b);
const ratio = color1luminance > color2luminance
? ((color2luminance + 0.05) / (color1luminance + 0.05))
: ((color1luminance + 0.05) / (color2luminance + 0.05));
console.log(ratio)
console.log((Math.floor(100 / ratio)) / 100 + ' : 1')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment