颜色rgba、16进制、10进制互相装换

rgba转16进制:

function RGBToHex(rgb){ 
   var regexp = /[0-9]{0,3}/g;  
   var re = rgb.match(regexp);//利用正则表达式去掉多余的部分,将rgb中的数字提取
   var hexColor = "#"; var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];  
   for (var i = 0; i < re.length; i++) {
        var r = null, c = re[i], l = c; 
        var hexAr = [];
        while (c > 16){  
              r = c % 16;  
              c = (c / 16) >> 0; 
              hexAr.push(hex[r]);  
         } hexAr.push(hex[c]);
         if(l < 16&&l != ""){        
             hexAr.push(0)
         }
       hexColor += hexAr.reverse().join(''); 
    }  
   //alert(hexColor)  
   return hexColor;  
} 

16进制转rgba:

var util = {
    cutHex: function (hex) {
        return hex.charAt(0) == "#" ? hex.substring(1, 7) : hex;
    },
    hexToR: function (hex) {
        return parseInt((util.cutHex(hex)).substring(0, 2), 16)
    },
    hexToG: function (hex) {
        return parseInt((util.cutHex(hex)).substring(2, 4), 16)
    },
    hexToB: function (hex) {
        return parseInt((util.cutHex(hex)).substring(4, 6), 16)
    },
    hexToRgba: function (hex) {
        return 'rgba('+util.hexToR(hex)+','+util.hexToG(hex)+','+util.hexToB(hex)+',0.1)';
    }
};

10进制转rgba(转自网络,未验证):

方法一:

function getColor(number) {
        let color = number;
        const blue = parseInt(color % 0x100, 10);
        color = color >>> 8;
        const green = parseInt(color % 0x100, 10);
        color = color >>> 8;
        const red = parseInt(color % 0x100, 10);
        const alpha = (parseInt(color >>> 8, 10) / 0xFF).toFixed(1);
        return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
    }

方法二:

function getColor(number) {
    const alpha = number >> 24 & 0xff;
    const red = number >> 16 & 0xff;
    const green = number >> 8 & 0xff;
    const blue = number & 0xff;
    return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
}

 

posted @ 2017-10-11 16:13  sunnyny  阅读(7368)  评论(0编辑  收藏  举报