-
-
Save thgh/7f63a2253c2ad3d6972a196b919b2481 to your computer and use it in GitHub Desktop.
Method to lighten / darken hex colors using Javascript.
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
export function lighten(color = '#004488', opacity = 1) { | |
// Convert to color channels | |
const num = parseInt(color.slice(1), 16) | |
let R = num >> 16, | |
G = (num >> 8) & 0x00ff, | |
B = num & 0x0000ff | |
// Interpolate channel | |
opacity = Math.min(Math.max(opacity, 0), 1) | |
R = Math.round(R + (1 - opacity) * (255 - R)) | |
G = Math.round(G + (1 - opacity) * (255 - G)) | |
B = Math.round(B + (1 - opacity) * (255 - B)) | |
// Encode as hex | |
return ( | |
'#' + | |
( | |
0x1000000 + | |
(R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 + | |
(G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 + | |
(B < 255 ? (B < 1 ? 0 : B) : 255) | |
) | |
.toString(16) | |
.slice(1) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment