javascript shifting issue (rgb and rgba to hex)

后端 未结 1 744
一整个雨季
一整个雨季 2021-01-20 03:55

I found a RGB to hex converter and I\'m trying to make a RGBA to hex converter. The original rgb2hex function works but the new rgba2hex function d

相关标签:
1条回答
  • 2021-01-20 04:50

    Your issue is that bitwise math in JavaScript caps out at 31 bits, so you can't quite do this as is. You need to use normal math ops, not bitwise ops:

    // 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);
    }
    

    Also fixed an issue with the original algorithm where if the first component is < 10, the output doesn't have enough digits.

    Anyway, this won't work anyway... #ff9b2dff isn't a valid color, but you may not care?

    0 讨论(0)
提交回复
热议问题