可能是重复问题:
将RGBA颜色转换为RGB
我正在尝试将一个带有alpha < 1的RGBA颜色转换为纯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中运行上述代码,当alpha为0.5时成功地将RGBA转换为RGB,任何偏离0.5的值都会导致不匹配,如果偏差非常小(即alpha为0.55时可能会注意到问题),则非常微妙。
我已经多次重写了逻辑,并将逻辑完全展开为其最基本的部分,但仍未成功。