RGB to hex and hex to RGB

前端 未结 30 2777
遥遥无期
遥遥无期 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条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 07:22

    My version of hex2rbg:

    1. Accept short hex like #fff
    2. Algorithm compacity is o(n), should faster than using regex. e.g String.replace, String.split, String.match etc..
    3. Use constant space.
    4. Support rgb and rgba.

    you may need remove hex.trim() if you are using IE8.

    e.g.

    hex2rgb('#fff') //rgb(255,255,255) 
    hex2rgb('#fff', 1) //rgba(255,255,255,1) 
    hex2rgb('#ffffff') //rgb(255,255,255)  
    hex2rgb('#ffffff', 1) //rgba(255,255,255,1)
    

    code:

    function hex2rgb (hex, opacity) {
        hex = hex.trim();
        hex = hex[0] === '#' ? hex.substr(1) : hex;
        var bigint = parseInt(hex, 16), h = [];
        if (hex.length === 3) {
            h.push((bigint >> 4) & 255);
            h.push((bigint >> 2) & 255);
        } else {
            h.push((bigint >> 16) & 255);
            h.push((bigint >> 8) & 255);
        }
        h.push(bigint & 255);
        if (arguments.length === 2) {
            h.push(opacity);
            return 'rgba('+h.join()+')';
        } else {
            return 'rgb('+h.join()+')';
        }
    }
    

提交回复
热议问题