-
-
Save pascaliske/7135a3c1cee50e75781e77b8658e9d53 to your computer and use it in GitHub Desktop.
Calculate difference in percentage between 2 hex colors
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
export function diff(color1: string, color2: string): number { | |
if (!color1 && !color2) { | |
return; | |
} | |
const _color1 = color1.charAt(0) == '#' ? color1.substring(1, 7) : color1; | |
const _color2 = color2.charAt(0) == '#' ? color2.substring(1, 7) : color2; | |
const rColor1 = parseInt(_color1.substring(0, 2), 16); | |
const gColor1 = parseInt(_color1.substring(2, 4), 16); | |
const bColor1 = parseInt(_color1.substring(4, 6), 16); | |
const rColor2 = parseInt(_color2.substring(0, 2), 16); | |
const gColor2 = parseInt(_color2.substring(2, 4), 16); | |
const bColor2 = parseInt(_color2.substring(4, 6), 16); | |
const p1color1 = rColor1 / 255 * 100; | |
const p2color1 = gColor1 / 255 * 100; | |
const p3color1 = bColor1 / 255 * 100; | |
const p1color2 = rColor2 / 255 * 100; | |
const p2color2 = gColor2 / 255 * 100; | |
const p3color2 = bColor2 / 255 * 100; | |
const perc1 = Math.round((p1color1 + p2color1 + p3color1) / 3); | |
const perc2 = Math.round((p1color2 + p2color2 + p3color2) / 3); | |
return Math.abs(perc1 - perc2); | |
} |
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
import { diff } from './diff' | |
diff('#ffffff', '#000000') // => 100 | |
diff('#2d333d', '#000000') // => 21 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment