Created
September 9, 2019 17:01
-
-
Save robshep/73a6ba10992411f83d0633e2fed4cef9 to your computer and use it in GitHub Desktop.
Convert RGBA on white to RGB
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
| // taken from here and made to work | |
| // | |
| var debug = false; | |
| //var rgbaColor = 'rgba(1,12,123,0.33)'; | |
| var rgbaColor = 'rgba(247, 224, 153, 0.247)'; | |
| // var rgbaColor = '#999'; | |
| // var rgbaColor = 'rgb(30, 20, 200)'; | |
| var rgbColor = convertRGBAtoRGBIfNeeded(rgbaColor) | |
| console.log('RGB', rgbColor) | |
| var rgbaElement = document.getElementById("rgba"); | |
| var rgbElement = document.getElementById("rgb"); | |
| setColor(rgbaElement, rgbaColor) | |
| setColor(rgbElement, rgbColor) | |
| function setColor(element, color) { | |
| if (!element) return; | |
| element.style.backgroundColor = color; | |
| } | |
| function convertRGBAtoRGBIfNeeded(colorCssString) { | |
| var isRGBA = function(colorCssString) { | |
| return colorCssString.match(/rgba/gi); | |
| } | |
| if (!isRGBA(colorCssString)) return colorCssString; | |
| var colorArray = colorCssString.match(/\d+\.*\d*/g); | |
| if (debug) console.log(colorArray); | |
| var rgb = colorCssString.match(/\d+\.*\d+/g); | |
| if (debug) console.log('rgb:', rgb); | |
| var Source = {}; | |
| Source.R = colorArray.shift()/255; | |
| Source.G = colorArray.shift()/255; | |
| Source.B = colorArray.shift()/255; | |
| Source.A = colorArray.shift()/1; | |
| if (debug) console.log(colorArray); | |
| if (debug) console.log(Source); | |
| var BGColor = { | |
| R: 1, | |
| G: 1, | |
| B: 1 | |
| }; | |
| // Credits to: | |
| // https://stackoverflow.com/questions/2049230/convert-rgba-color-to-rgb | |
| var Target = {}; | |
| Target.R = parseInt(255 * (((1 - Source.A) * BGColor.R) + (Source.A * Source.R))); | |
| Target.G = parseInt(255 * (((1 - Source.A) * BGColor.G) + (Source.A * Source.G))); | |
| Target.B = parseInt(255 * (((1 - Source.A) * BGColor.B) + (Source.A * Source.B))); | |
| if (debug) console.log(Target); | |
| var rgbColor2 = 'rgb(' + Target.R + ',' + Target.G + ',' + Target.B + ')'; | |
| return rgbColor2; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment