-
-
Save ncou/0957c56a8cf3677e7afb18e8844060b3 to your computer and use it in GitHub Desktop.
Javascript parse colours (Hex to RGB and vice versa) as well as luminance(dark or bright)
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
| /** | |
| * Original code from https://github.com/mike-schultz/materialette | |
| */ | |
| function rgbToHex(r, g, b) { | |
| return "#" + ((1 << 24) + (parseInt(r) << 16) + (parseInt(g) << 8) + parseInt(b)).toString(16).slice(1); | |
| } | |
| function hexToRgb(hex) { | |
| const 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; | |
| } | |
| /** | |
| * luminance(hex, '#fff', '#000') | |
| */ | |
| function luminance(sHexColor, sLight, sDark) { | |
| const oRGB = hexToRgb(sHexColor); | |
| const yiq = ((oRGB.r * 299) + (oRGB.g * 587) + (oRGB.b * 114)) / 1000; | |
| return (yiq >= 128) ? sDark : sLight; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment