How to convert rgba to a transparency-adjusted-hex?

后端 未结 3 1541
执笔经年
执笔经年 2021-01-30 10:57

I\'m wondering how to convert rgba into hex in a way that translates the visible rgba-color (including transparency) into a hex value.

Say I ha

3条回答
  •  迷失自我
    2021-01-30 11:42

    function hexify(color) {
      var values = color
        .replace(/rgba?\(/, '')
        .replace(/\)/, '')
        .replace(/[\s+]/g, '')
        .split(',');
      var a = parseFloat(values[3] || 1),
          r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
          g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
          b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
      return "#" +
        ("0" + r.toString(16)).slice(-2) +
        ("0" + g.toString(16)).slice(-2) +
        ("0" + b.toString(16)).slice(-2);
    }
    
    var myHex = hexify('rgba(57,156,29,0.05)'); // "#f5faf3"
    
    console.log(myHex);

提交回复
热议问题