Created
January 16, 2024 16:17
-
-
Save yojona/976d00ff387ea66ba7aeff71bd13b019 to your computer and use it in GitHub Desktop.
hex alpha
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 const alpha = (color: string, opacity: number) => { | |
// if it has an alpha, remove it | |
if (color.length > 7) { | |
color = color.substring(0, color.length - 2); | |
} | |
// coerce values so ti is between 0 and 1. | |
const newOpacity = Math.round(Math.min(Math.max(opacity, 0), 1) * 255); | |
let opacityHex = newOpacity.toString(16).toUpperCase(); | |
// opacities near 0 need a trailing 0 | |
if (opacityHex.length === 1) { | |
opacityHex = `0${opacityHex}`; | |
} | |
return color + opacityHex; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment