Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

javascript - 在白色上将RGB转换为RGBA(Convert RGB to RGBA over white)

I have a hex color, eg #F4F8FB (or rgb(244, 248, 251) ) that I want converted into an as-transparent-as-possible rgba color (when displayed over white).(我有一个十六进制颜色,例如#F4F8FB (或rgb(244, 248, 251) #F4F8FB rgb(244, 248, 251) ),我想将其转换为尽可能透明的 rgba颜色(当显示为白色时)。)

Make sense?(说得通?) I'm looking for an algorithm, or at least idea of an algorithm for how to do so.(我正在寻找一种算法,或者至少是关于一种算法的构想。)

For Example:(例如:)

rgb( 128, 128, 255 ) --> rgba(   0,   0, 255,  .5 )
rgb( 152, 177, 202 ) --> rgba(  50, 100, 150,  .5 ) // can be better(lower alpha)

Ideas?(有想法吗?)


FYI solution based on Guffa's answer:(基于Guffa答案的FYI解决方案:)

function RGBtoRGBA(r, g, b){
    if((g == null) && (typeof r === 'string')){
        var hex = r.replace(/^s*#|s*$/g, '');
        if(hex.length === 3){
            hex = hex.replace(/(.)/g, '$1$1');
        }
        r = parseInt(hex.substr(0, 2), 16);
        g = parseInt(hex.substr(2, 2), 16);
        b = parseInt(hex.substr(4, 2), 16);
    }

    var min, a = (255 - (min = Math.min(r, g, b))) / 255;

    return {
        r    : r = 0|(r - min) / a,
        g    : g = 0|(g - min) / a,
        b    : b = 0|(b - min) / a,
        a    : a = (0|1000*a)/1000,
        rgba : 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')'
    };
}

RGBtoRGBA(204, 153, 102) == RGBtoRGBA('#CC9966') == RGBtoRGBA('C96') == 
    {
       r    : 170,
       g    : 85 ,
       b    : 0  ,
       a    : 0.6,
       rgba : 'rgba(170, 85, 0, 0.6)' 
    }
  ask by Mark Kahn translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Take the lowest color component, and convert that to an alpha value.(取最低的颜色分量,并将其转换为alpha值。)

Then scale the color components by subtracting the lowest, and dividing by the alpha value.(然后,通过减去最低值并除以alpha值来缩放颜色分量。)

Example:(例:)

152 converts to an alpha value of (255 - 152) / 255 ~ 0.404

152 scales using (152 - 152) / 0.404 = 0
177 scales using (177 - 152) / 0.404 ~ 62
202 scales using (202 - 152) / 0.404 ~ 123

So, rgb(152, 177, 202) displays as rgba(0, 62, 123, .404) .(因此, rgb(152, 177, 202) rgba(0, 62, 123, .404) rgb(152, 177, 202)显示为rgba(0, 62, 123, .404) 。)

I have verified in Photoshop that the colors actually match perfectly.(我已经在Photoshop中验证颜色实际上完全匹配。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...