How is opacity calculated mathematically?
There is opacity value in Photoshop, CSS etc. Actually this opacity is the transparent behavior of a layer. That we all kno
The formula for combining C1 = (R1,G1,B1)
and C2 = (R2,G2,B2)
into a new color C3, where C2 is overlayed on top of C1 with opacity p is usually ( (1-p)R1 + p*R2, (1-p)*G1 + p*G2, (1-p)*B1 + p*B2 )
.
See Wikipedia article on transparency for more information.
The following javascript gives a method that can be used to calculate the opacity color value manually:
function calculateTransparentColor(foregroundColor, backgroundColor, opacity) {
if (opacity < 0.0 || opacity > 1.0) {
alert("assertion, opacity should be between 0 and 1");
}
opacity = opacity * 1.0; // to make it float
let foregroundRGB = colorHexToRGB(foregroundColor);
let backgroundRGB = colorHexToRGB(backgroundColor);
let finalRed = Math.round(backgroundRGB.r * (1-opacity) + foregroundRGB.r * opacity);
let finalGreen = Math.round(backgroundRGB.g * (1-opacity) + foregroundRGB.g * opacity);
let finalBlue = Math.round(backgroundRGB.b * (1-opacity) + foregroundRGB.b * opacity);
return colorRGBToHex(finalRed, finalGreen, finalBlue);
}
var COLOR_REGEX = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/;
function colorHexToRGB(htmlColor) {
let arrRGB = htmlColor.match(COLOR_REGEX);
if (arrRGB == null) {
alert("Invalid color passed, the color should be in the html format. Example: #ff0033");
}
let red = parseInt(arrRGB[1], 16);
let green = parseInt(arrRGB[2], 16);
let blue = parseInt(arrRGB[3], 16);
return {"r":red, "g":green, "b":blue};
}
function colorRGBToHex(red, green, blue) {
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) {
alert("Invalid color value passed. Should be between 0 and 255.");
}
let hexRed = formatHex(red.toString(16));
let hexGreen = formatHex(green.toString(16));
let hexBlue = formatHex(blue.toString(16));
return "#" + hexRed + hexGreen + hexBlue;
}
function formatHex(value) {
value = value + "";
if (value.length == 1) {
return "0" + value;
}
return value;
}
// Now we test it!
let theColor = calculateTransparentColor('#ff0000', '#00ff00', 0.5)
console.log("The color #ff0000 on a background of #00ff00 with 50% opacity produces: " + theColor);
Formula for Result of mixing two transparent pixels:
C1=[R1,G1,B1] is the foreground pixel color.
C2=[R2,G2,B2] is the background pixel color.
p1 is the opacity percentage of the foreground pixel.
p2 is the opacity percentage of the background pixel.
New_Pixel_Color = (p1*c1+p2*c2-p1*p2*c2)/(p1+p2-p1*p2)
New_Pixel_opacity = p1+p2-p1*p2
You can test and enjoy it!