js中rgba颜色和hex互相转换

有时候我们需要将服务端下发的rgba色或者hex之间做互相转换以便使用或上报,我将两者之间的转换封装代码如下:

// 将rgb颜色转成hex
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;
}
// 将hex颜色转成rgb
function hexToRgba(hex, opacity) {
    var RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," + parseInt( "0x" + hex.slice(5, 7)) + "," + opacity + ")";
    return {
        red: parseInt("0x" + hex.slice(1, 3)),
        green: parseInt("0x" + hex.slice(3, 5)),
        blue: parseInt("0x" + hex.slice(5, 7)),
        rgba: RGBA
    }
}

rgb色转成hex : colorRGB2Hex(“rgb(255,255,255)”); 返回hex值 如#cccccc
hex转成rgba: hexToRgba("#cccccc", 1); // 第一个参数为hex色值,第二个参数为透明度,返回对象

你可能感兴趣的:(原生JavaScript)