Created
April 27, 2021 08:02
-
-
Save a666hn/37d1e94d7376280b9e039d5f8050c4bf to your computer and use it in GitHub Desktop.
Generate contrast text!!!
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
function setContrastText(hexColor="", isBlackAndWhite=false) { | |
if (!hexColor) return "black" | |
if (hexColor.slice(0, 1) === "#") { | |
hexColor = hexColor.slice(1) | |
} | |
if (hexColor.length === 3) { | |
hexColor = hexColor.repeat(2) | |
} | |
let r = parseInt(hexColor.substr(0,2),16) | |
let g = parseInt(hexColor.substr(2,2),16) | |
let b = parseInt(hexColor.substr(4,2),16) | |
let yiq = ((r * 0.299) + (g * 0.587) + (b * 0.114)) | |
if (isBlackAndWhite) { | |
return yiq > 186 ? "#000000" : "#FFFFFF" | |
} | |
r = (255 - r).toString(16) | |
g = (255 - g).toString(16) | |
b = (255 - b).toString(16) | |
return `#${padZero(r)}${padZero(g)}${padZero(b)}` | |
} | |
function padZero(str, len) { | |
len = len || 2; | |
var zeros = new Array(len).join('0'); | |
return (zeros + str).slice(-len); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment