Created
September 14, 2018 13:27
-
-
Save negarjf/18424afd9786fac1b932ba7df7172777 to your computer and use it in GitHub Desktop.
Auto Text Color Detector
This file contains 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
// Converts color code to RGB | |
//==================================== | |
function colorCodeToRGB(colorCode){ | |
var c; | |
var rgbaValidation = (/([R][G][B][A]?[(]\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])(\s*,\s*((0\.[0-9]{1})|(1\.0)|(1)))?[)])/i.test(colorCode)) ; | |
var hexValidation = (/^#([A-Fa-f0-9]{3}){1,2}$/.test(colorCode)); | |
if(hexValidation){ | |
c= colorCode.substring(1).split(''); | |
if(c.length== 3){ | |
c= [c[0], c[0], c[1], c[1], c[2], c[2]]; | |
} | |
c= '0x'+c.join(''); | |
return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')'; | |
}else if(rgbaValidation){ | |
return colorCode; | |
} | |
return colorCode; | |
} | |
// Detects text color based on given color | |
//===================================== | |
function autoTextColor(bgColor, lightColor, darkColor){ | |
var lightTextColor = (typeof lightColor === "string")? lightColor : "#fff"; | |
var darkTextColor = (typeof darkColor === "string")? darkColor : "#333"; | |
var rgbString = colorCodeToRGB(bgColor); | |
var matchColors = /rgb\((\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\)/; | |
var rgb = matchColors.exec(rgbString); | |
if (rgb === null) { | |
return; | |
} | |
var o = Math.round(((parseInt(rgb[1]) * 299) + | |
(parseInt(rgb[2]) * 587) + | |
(parseInt(rgb[3]) * 114)) / 1000); | |
return (o > 125) ? darkTextColor : lightTextColor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment