RGB to hex and hex to RGB

前端 未结 30 2872
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  猫巷女王i
    2020-11-21 07:08

    @ Tim, to add to your answer (its a little awkward fitting this into a comment).

    As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.

    I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.

    function rgbToHex(r, g, b) {
        if(r < 0 || r > 255) alert("r is out of bounds; "+r);
        if(g < 0 || g > 255) alert("g is out of bounds; "+g);
        if(b < 0 || b > 255) alert("b is out of bounds; "+b);
        return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
    }
    

提交回复
热议问题