Created
October 26, 2017 16:37
-
-
Save SinBirb/f71ab664d6f6bd3bbea7992bb264f2cf to your computer and use it in GitHub Desktop.
Heuristic to check whether a site appears dark or bright to a user
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* round num to c digits */ | |
function round(num, c) { | |
return +(Math.round(num + "e+" + c) + "e-" + c); | |
} | |
/* Adapted from Python from manojpandey, thanks! | |
https://gist.github.com/manojpandey/f5ece715132c572c80421febebaf66ae | |
*/ | |
function rgbTolab(inputColor) { | |
var num = 0; | |
var RGB = [0, 0, 0]; | |
inputColor.forEach(function(value) { | |
value = parseFloat(value) / 255; | |
if (value > 0.04045) { | |
value = ((value + 0.055) / 1.055) ** 2.4; | |
} | |
else { | |
value = value / 12.92; | |
} | |
RGB[num] = value * 100; | |
num = num + 1; | |
}); | |
var XYZ = [0, 0, 0]; | |
var X = RGB[0] * 0.4124 + RGB[1] * 0.3576 + RGB[2] * 0.1805; | |
var Y = RGB[0] * 0.2126 + RGB[1] * 0.7152 + RGB[2] * 0.0722; | |
var Z = RGB[0] * 0.0193 + RGB[1] * 0.1192 + RGB[2] * 0.9505; | |
XYZ[0] = round(X, 4); | |
XYZ[1] = round(Y, 4); | |
XYZ[2] = round(Z, 4); | |
// Observer= 2°, Illuminant= D65 | |
XYZ[0] = parseFloat(XYZ[0]) / 95.047; // ref_X = 95.047 | |
XYZ[1] = parseFloat(XYZ[1]) / 100.0; // ref_Y = 100.000 | |
XYZ[2] = parseFloat(XYZ[2]) / 108.883; // ref_Z = 108.883 | |
var num = 0; | |
XYZ.forEach(function(value) { | |
if (value > 0.008856) { | |
value = value ** (0.3333333333333333); | |
} | |
else { | |
value = (7.787 * value) + (16 / 116); | |
} | |
XYZ[num] = value; | |
num = num + 1; | |
}); | |
var Lab = [0, 0, 0]; | |
var L = (116 * XYZ[1]) - 16; | |
var a = 500 * (XYZ[0] - XYZ[1]); | |
var b = 200 * (XYZ[1] - XYZ[2]); | |
Lab[0] = round(L, 4); | |
Lab[1] = round(a, 4); | |
Lab[2] = round(b, 4); | |
return Lab; | |
} | |
var mainTextColor = window.getComputedStyle(document.body, null).color; | |
var brightness = rgbTolab(mainTextColor.match(/\d+/g))[0]; | |
var threshold = 50; | |
if (brightness < threshold) { | |
console.log("This page has some dark text. Better use dark mode."); | |
} | |
else { | |
console.log("This page has some bright text. Better leave it like that."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment