RGB to hex and hex to RGB

前端 未结 30 2813
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  心在旅途
    2020-11-21 07:29

    An alternative version of hexToRgb:

    function hexToRgb(hex) {
        var bigint = parseInt(hex, 16);
        var r = (bigint >> 16) & 255;
        var g = (bigint >> 8) & 255;
        var b = bigint & 255;
    
        return r + "," + g + "," + b;
    }
    

    Edit: 3/28/2017 Here is another approach that seems to be even faster

    function hexToRgbNew(hex) {
      var arrBuff = new ArrayBuffer(4);
      var vw = new DataView(arrBuff);
      vw.setUint32(0,parseInt(hex, 16),false);
      var arrByte = new Uint8Array(arrBuff);
    
      return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
    }
    

    Edit: 8/11/2017 The new approach above after more testing is not faster :(. Though it is a fun alternate way.

提交回复
热议问题