Skip to content

Instantly share code, notes, and snippets.

@yojona
Created January 16, 2024 16:17
Show Gist options
  • Save yojona/976d00ff387ea66ba7aeff71bd13b019 to your computer and use it in GitHub Desktop.
Save yojona/976d00ff387ea66ba7aeff71bd13b019 to your computer and use it in GitHub Desktop.
hex alpha
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