Created
October 21, 2023 09:16
-
-
Save serkodev/b15058127f834fe0b6da92d9cfebcca5 to your computer and use it in GitHub Desktop.
Calculate alpha from background color, source color and final color
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
| function calculateAlpha(bgColor, srcColor, finalColor) { | |
| // Convert a hex color to its rgb components | |
| function hexToRgb(hex) { | |
| const bigint = parseInt(hex.replace("#", ""), 16); | |
| return { | |
| r: (bigint >> 16) & 255, | |
| g: (bigint >> 8) & 255, | |
| b: bigint & 255, | |
| }; | |
| } | |
| const rgbBg = hexToRgb(bgColor); | |
| const rgbSrc = hexToRgb(srcColor); | |
| const rgbFinal = hexToRgb(finalColor); | |
| // Calculate alpha for each channel | |
| const alphaR = (rgbFinal.r - rgbBg.r) / (rgbSrc.r - rgbBg.r); | |
| const alphaG = (rgbFinal.g - rgbBg.g) / (rgbSrc.g - rgbBg.g); | |
| const alphaB = (rgbFinal.b - rgbBg.b) / (rgbSrc.b - rgbBg.b); | |
| // Check if the alpha values are consistent across all channels | |
| if (Math.abs(alphaR - alphaG) < 0.01 && Math.abs(alphaG - alphaB) < 0.01) { | |
| return (alphaR + alphaG + alphaB) / 3; // Return average alpha | |
| } else { | |
| throw new Error("Inconsistent alphas across channels. Cannot compute a single alpha value."); | |
| } | |
| } | |
| // Test the function | |
| const bgColor = "#ffffff"; | |
| const srcColor = "#404040"; | |
| const finalColor = "#737373"; | |
| console.log(calculateAlpha(bgColor, srcColor, finalColor)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment