Convert Hex to RGBA

后端 未结 18 806
南方客
南方客 2020-12-04 11:36

My fiddle - http://jsbin.com/pitu/1/edit

I wanted to try an easy hex to rgba conversion. Ever browser I\'ve used renders colors using rgb as default so when using th

相关标签:
18条回答
  • 2020-12-04 12:27

    Pure JS solution if it helps:

    function hexToRGB(hex,alphaYes){
     var h = "0123456789ABCDEF";
     var r = h.indexOf(hex[1])*16+h.indexOf(hex[2]);
     var g = h.indexOf(hex[3])*16+h.indexOf(hex[4]);
     var b = h.indexOf(hex[5])*16+h.indexOf(hex[6]);
     if(alphaYes) return "rgba("+r+", "+g+", "+b+", 1)";
     else return "rgb("+r+", "+g+", "+b+")";
    }
    

    "alphaYes" is "true" or "false" depending upon whether you want the alpha or not.

    Preview

    0 讨论(0)
  • 2020-12-04 12:27

    I liked the @AJFarkas answer and append the support for shortcut hex (#fff) to it

    function hexToRGB(hex, alpha) {
        if (!hex || [4, 7].indexOf(hex.length) === -1) {
            return; // throw new Error('Bad Hex');
        }
    
        hex = hex.substr(1);
        // if shortcuts (#F00) -> set to normal (#FF0000)
        if (hex.length === 3) { 
            hex = hex.split('').map(function(el){ 
                  return el + el + '';
                }).join('');
        }
    
        var r = parseInt(hex.slice(0, 2), 16),
            g = parseInt(hex.slice(2, 4), 16),
            b = parseInt(hex.slice(4, 6), 16);
    
        if (alpha !== undefined) {
            return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
        } else {
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    }
    
    document.write(hexToRGB('#FF0000', 0.5));
    document.write('<br>');
    document.write(hexToRGB('#F00', 0.4));

    0 讨论(0)
  • 2020-12-04 12:28

    No need to re-implement the wheel:

    • RGB to HEX: https://github.com/sindresorhus/rgb-hex
    • HEX to RGB: https://github.com/sindresorhus/hex-rgb
    0 讨论(0)
  • 2020-12-04 12:29

    Any Hex Form Modular Approach

    The main challenge is that as of 2018 there are a few forms of HEX. The 6 char traditional form, the 3 char shorten form, and a new 4 and 8 char form that includes alpha. The following function can handle any HEX form.

    const isValidHex = (hex) => /^#([A-Fa-f0-9]{3,4}){1,2}$/.test(hex)
    
    const getChunksFromString = (st, chunkSize) => st.match(new RegExp(`.{${chunkSize}}`, "g"))
    
    const convertHexUnitTo256 = (hexStr) => parseInt(hexStr.repeat(2 / hexStr.length), 16)
    
    const getAlphafloat = (a, alpha) => {
        if (typeof a !== "undefined") {return a / 255}
        if ((typeof alpha != "number") || alpha <0 || alpha >1){
          return 1
        }
        return alpha
    }
    
    export const hexToRGBA = (hex, alpha) => {
        if (!isValidHex(hex)) {throw new Error("Invalid HEX")}
        const chunkSize = Math.floor((hex.length - 1) / 3)
        const hexArr = getChunksFromString(hex.slice(1), chunkSize)
        const [r, g, b, a] = hexArr.map(convertHexUnitTo256)
        return `rgba(${r}, ${g}, ${b}, ${getAlphafloat(a, alpha)})`
    }
    

    Alpha could be provided to the function in the following ways:

    1. As part of a 4, or 8 form HEX .
    2. As a second parameter between 0-1,

    OutPut

        const c1 = "#f80"
        const c2 = "#f808"
        const c3 = "#0088ff"
        const c4 = "#0088ff88"
        const c5 = "#98736"
    
        console.log(hexToRGBA(c1))   //  rgba(255, 136, 0, 1)
        console.log(hexToRGBA(c2))   //  rgba(255, 136, 0, 0.53125)
        console.log(hexToRGBA(c3))   //  rgba(0, 136, 255, 1)
        console.log(hexToRGBA(c4))   //  rgba(0, 136, 255, 0.53125)
        console.log(hexToRGBA(c5))   //  Uncaught Error: Invalid HEX
    
        console.log(hexToRGBA(c1, 0.5))   //  rgba(255, 136, 0, 0.5)
        console.log(hexToRGBA(c3, 0.5))   //  rgba(0, 136, 255, 0.5)
    
    0 讨论(0)
  • 2020-12-04 12:30

    @ElDoRado1239 has the right idea, but there's also a cleaner way:

    function hexToRGB(hex, alpha) {
        var r = parseInt(hex.slice(1, 3), 16),
            g = parseInt(hex.slice(3, 5), 16),
            b = parseInt(hex.slice(5, 7), 16);
    
        if (alpha) {
            return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
        } else {
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    }
    
    hexToRGB('#FF0000', 0.5);

    0 讨论(0)
  • 2020-12-04 12:32

    Try This

    <div class="torgb" onclick="rgba();" style="background-color:#000; width:20px; height:20px;"></div>
    <script>
    function rgba(){
    $('.torgb').attr('background-color','rgba(0,0,0,1)');
    $('.torgb').attr('onclick','hex();');
    }
    function hex(){
    $('.torgb').attr('background-color','#000');
    $('.torgb').attr('onclick','rgba();');
    }
    </script>
    
    0 讨论(0)
提交回复
热议问题