【问题标题】:javascript shifting issue (rgb and rgba to hex)javascript 转换问题(rgb 和 rgba 到 hex)
【发布时间】:2012-04-03 16:04:20
【问题描述】:

我找到了一个 RGB 到十六进制转换器,我正在尝试制作一个 RGBA 到十六进制转换器。原来的 rgb2hex 函数有效,但新的 rgba2hex 函数无效。我究竟做错了什么? rgba 函数返回 gba,没有 r。

// convert RGB color data to hex
function rgb2hex(r, g, b) {
    if (r > 255 || g > 255 || b > 255)
        throw "Invalid color component";
    return ((r << 16) | (g << 8) | b).toString(16);
}

// convert RGBA color data to hex
function rgba2hex(r, g, b, a) {
    if (r > 255 || g > 255 || b > 255 || a > 255)
        throw "Invalid color component";
    return ((r << 32) | (g << 16) | (b << 8) | a).toString(16);
}

例子:

alert(rgb2hex(255, 155, 055));
alert(rgba2hex(255, 155, 055, 255));

当前输出:ff9b2d9b2dff

预期输出:ff9b2dff9b2dff

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您的问题是 JavaScript 中的按位数学上限为 31 位,因此您不能完全按原样执行此操作。您需要使用普通的数学运算,而不是按位运算:

    // convert RGBA color data to hex
    function rgba2hex(r, g, b, a) {
        if (r > 255 || g > 255 || b > 255 || a > 255)
            throw "Invalid color component";
        return (256 + r).toString(16).substr(1) +((1 << 24) + (g << 16) | (b << 8) | a).toString(16).substr(1);
    }
    

    还修复了原始算法的一个问题,即如果第一个分量

    无论如何,这无论如何都行不通...#ff9b2dff 不是有效颜色,但您可能不在乎?

    【讨论】:

      【解决方案2】:

      RGB 转十六进制

       rgb(0 255 94)
       rgb(0, 255, 94)
      

      RGBA 转十六进制

       rgba(255,25,2,0.5)
       rgba(255 25 2 / 0.5)
       rgba(50%,30%,10%,0.5)
       rgba(50%,30%,10%,50%)
       rgba(50% 30% 10% / 0.5)
       rgba(50% 30% 10% / 50%)
      

      DEMO - CODEPEN.IO

      【讨论】:

        猜你喜欢
        • 2018-02-25
        • 2011-10-04
        • 2013-03-28
        • 2011-10-04
        • 2012-03-05
        • 2014-03-01
        • 2020-08-22
        • 2016-08-11
        相关资源
        最近更新 更多