js 颜色hex和rgba进行互转

js yekong

要在JavaScript中进行RGBA与HEX之间的转换,你可以使用以下函数:

  1. RGBA到HEX:

    function rgbaToHex(r, g, b, a) {
        r = r.toString(16);
        g = g.toString(16);
        b = b.toString(16);
        a = Math.round(a * 255).toString(16);
    
        if (r.length == 1) r = "0" + r;
        if (g.length == 1) g = "0" + g;
        if (b.length == 1) b = "0" + b;
        if (a.length == 1) a = "0" + a;
    
        return "#" + r + g + b + a;
    }
    
  2. HEX到RGBA:

    function hexToRgba(hex) {
        let r = parseInt(hex.slice(1, 3), 16),
            g = parseInt(hex.slice(3, 5), 16),
            b = parseInt(hex.slice(5, 7), 16),
            a = parseInt(hex.slice(7, 9), 16) / 255;
    
        return `rgba(``{r}, ``{g}, ``{b}, ``{a.toFixed(2)})`;
    }
    

使用示例:

  • 使用rgbaToHex:

    let hex = rgbaToHex(255, 255, 255, 0.5);  // "#FFFFFF80"
    
  • 使用hexToRgba:

    let rgba = hexToRgba("#FFFFFF80");  // "rgba(255, 255, 255, 0.50)"
    

注意: 这里的转换是考虑了透明度(Alpha值)。如果你只需要RGB和HEX之间的转换,可以简单地省略与透明度相关的部分。

喜欢