Convert Hex to RGBA

后端 未结 18 943
南方客
南方客 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:26

    Here is a function that returns rgb or rgba if you provide an alpha. The function also converts short hex color codes too.

    function:

    function hexToRgb(hex, alpha) {
       hex   = hex.replace('#', '');
       var r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16);
       var g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16);
       var b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16);
       if ( alpha ) {
          return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')';
       }
       else {
          return 'rgb(' + r + ', ' + g + ', ' + b + ')';
       }
    }
    

    examples:

    hexToRgb('FF0000');// rgb(255, 0, 0)
    hexToRgb('#FF0000');// rgb(255, 0, 0)
    hexToRgb('#FF0000', 1);// rgba(255, 0, 0, 1)
    hexToRgb('F00');// rgb(255, 0, 0)
    hexToRgb('#F00');// rgb(255, 0, 0)
    hexToRgb('#F00', 1);// rgba(255, 0, 0, 1)
    

提交回复
热议问题