how to get contrast from a color using js

Solutions on MaxInterview for how to get contrast from a color using js by the best coders in the world

showing results for - "how to get contrast from a color using js"
Alissa
16 Jul 2016
1function invertColor(hex, bw) {
2    if (hex.indexOf('#') === 0) {
3        hex = hex.slice(1);
4    }
5    // convert 3-digit hex to 6-digits.
6    if (hex.length === 3) {
7        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
8    }
9    if (hex.length !== 6) {
10        throw new Error('Invalid HEX color.');
11    }
12    var r = parseInt(hex.slice(0, 2), 16),
13        g = parseInt(hex.slice(2, 4), 16),
14        b = parseInt(hex.slice(4, 6), 16);
15    if (bw) {
16        // http://stackoverflow.com/a/3943023/112731
17        return (r * 0.299 + g * 0.587 + b * 0.114) > 186
18            ? '#000000'
19            : '#FFFFFF';
20    }
21    // invert color components
22    r = (255 - r).toString(16);
23    g = (255 - g).toString(16);
24    b = (255 - b).toString(16);
25    // pad each with zeros and return
26    return "#" + padZero(r) + padZero(g) + padZero(b);
27}
28