spi*_*der 13 equation colors opacity mathematical-expressions
不透明度如何以数学方式计算?
在Photoshop,CSS等中存在不透明度值.实际上,这种不透明度是图层的透明行为.我们都知道.但它是如何以数学方式计算的?有没有计算不透明度的等式?
通过设置不透明度值,那里发生了什么?
以纯色图层为例:第1层(前景层)和第2层(背景层)
第1层是红色(比如颜色值A),第2层是白色(比如颜色值B).
当我们将不透明度(比方说p)设置为第1层时,我们可以放置0.5或50%并获得白红色(比如颜色值X).
为了获得这个价值,X我应该以数学方式做什么?
即.
X = (things which will be a relation containing p, A and B)
Run Code Online (Sandbox Code Playgroud)
我想知道要找到的确切数学方程式X.
另外,如果我有方程式,颜色值本质上是十六进制的,那么使用十六进制计算器可以得到正确的结果吗?
ipa*_*lic 24
用于将C1 = (R1,G1,B1)和C2 =组合(R2,G2,B2)成新颜色C3的公式,其中C2 通常用不透明度p覆盖在C1的顶部.( (1-p)R1 + p*R2, (1-p)*G1 + p*G2, (1-p)*B1 + p*B2 )
有关更多信息,请参阅Wikipedia关于透明度的文章
以下javascript提供了一种方法,可用于手动计算不透明度颜色值:
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);
Run Code Online (Sandbox Code Playgroud)