可能重复:
将RGBA颜色转换为RGB
我正在尝试转换RGBA颜色;1转换为考虑背景颜色的实心RGB表示。
使用这个问题中提供的算法,我设法获得了正确的RGB纯色转换——但只有当alpha=0.5时。
这是我的测试代码:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
// Basic RGB(A) to CSS property value
function _toString(obj) {
var type = 'rgb', out = obj.red + ', ' + obj.green + ', ' + obj.blue;
if (obj.alpha !== undefined) {
type += 'a';
out += ', ' + obj.alpha;
}
return type + '(' + out + ')';
}
// Background color, assume this is always RGB
var bg = {red: 255, green: 51, blue: 0};
// RGBA color
var RGBA = {red: 0, green: 102, blue: 204, alpha: 0};
// Output RGB
var RGB = {red: null, green: null, blue: null};
// Just a cache...
var alpha;
while (RGBA.alpha < 1) {
alpha = 1 - RGBA.alpha;
RGB.red = Math.round((alpha * (RGBA.red / 255) + ((1 - RGBA.alpha) * (bg.red / 255))) * 255);
RGB.green = Math.round((alpha * (RGBA.green / 255) + ((1 - RGBA.alpha) * (bg.green / 255))) * 255);
RGB.blue = Math.round((alpha * (RGBA.blue / 255) + ((1 - RGBA.alpha) * (bg.blue / 255))) * 255);
document.write('<div style="display: block; width: 150px; height: 100px; background-color: ' + _toString(bg) + '">
<div style="color: #fff; width: 50px; height: 50px; background-color: ' + _toString(RGBA) + '"><small>RGBA<br>' + RGBA.alpha + '</small></div>
<div style="color: #fff; width: 50px; height: 50px; background-color: ' + _toString(RGB) + '"><small>RGB<br>' + RGBA.alpha + '</small></div>
</div>');
// Increment alpha
RGBA.alpha += 0.25;
}
</script>
</body>
</html>
在Chrome和Firefox中运行以上操作会导致RGBA->RGB成功,当alpha为0.5时,任何偏离0.5的偏差都会导致不匹配,如果偏差很小,则会非常微妙(即,当alpha是0.55时,可能会注意到问题)。
我已经重写了好几次逻辑,将逻辑完全扩展到最基本的部分,但我都没能成功。
看起来你正在尝试使用通用的混合方法,但增量循环让我很失望。摘自OpenGL常见问题解答:
"上述(用于混合)的典型用途通过其相关的阿尔法值修改输入颜色,并通过一减去输入阿尔法值修改目标颜色。然后将这两种颜色的总和写回帧缓冲区。"
因此,不要使用while循环,而是使用:
alpha = 1 - RGBA.alpha;
RGB.red = Math.round((RGBA.alpha * (RGBA.red / 255) + (alpha * (bg.red / 255))) * 255);
RGB.green = Math.round((RGBA.alpha * (RGBA.green / 255) + (alpha * (bg.green / 255))) * 255);
RGB.blue = Math.round((RGBA.alpha * (RGBA.blue / 255) + (alpha * (bg.blue / 255))) * 255);