RGB颜色和16进制的转换

2017-05-06  本文已影响86人  尤樊容

RGB颜色转换成16进制:

        var str = "rgb(255,0,0)";
        function colorRGB2Hex(color) {
            var rgb = color.split(',');
            var r = parseInt(rgb[0].split('(')[1]);
            var g = parseInt(rgb[1]);
            var b = parseInt(rgb[2].split(')')[0]);

            var hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
            return hex;
        }
        console.log(colorRGB2Hex(str));//ff0000

16进制转换成RGB颜色,自己写了一个可是没有别人写的高级,所以有所借鉴,感谢Sara

        var str = "#f00";
        var reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
        function ColorHex2Rgb(hex){
            var HexColor = hex.toLowerCase();
            if(HexColor && reg.test(HexColor)){

                if(HexColor.length === 4){
                    var sColorNew = "#";
                    for(var i=1; i<4; i+=1){
                        sColorNew += HexColor.slice(i,i+1).concat(HexColor.slice(i,i+1));
                    }
                    HexColor = sColorNew;
                }
                var sColorChange = [];
                for(var i=1; i<7; i+=2){
                    sColorChange.push(parseInt("0x"+HexColor.slice(i,i+2)));
                }
                // return "RGB(" + sColorChange.join(",") + ")";
                return  sColorChange;
            }else{
                return HexColor;
            }
        }
        console.log(ColorHex2Rgb(str));
上一篇下一篇

猜你喜欢

热点阅读