RGB to hex and hex to RGB

前端 未结 30 2772
遥遥无期
遥遥无期 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:12

    This snippet converts hex to rgb and rgb to hex.

    View demo

    function hexToRgb(str) { 
        if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) { 
            var hex = str.substr(1);
            hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;
            var rgb = parseInt(hex, 16);               
            return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
        } 
    
        return false; 
    }
    
    function rgbToHex(red, green, blue) {
        var out = '#';
    
        for (var i = 0; i < 3; ++i) {
            var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);
    
            if (isNaN(n) || n < 0 || n > 255) {
                return false;
            }
    
            out += (n < 16 ? '0' : '') + n.toString(16);
        }
        return out
    }
    

提交回复
热议问题