RGB to hex and hex to RGB

前端 未结 30 2835
遥遥无期
遥遥无期 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:14

    ECMAScript 6 version of Tim Down's answer

    Converting RGB to hex

    const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => {
      const hex = x.toString(16)
      return hex.length === 1 ? '0' + hex : hex
    }).join('')
    
    console.log(rgbToHex(0, 51, 255)); // '#0033ff'

    Converting hex to RGB

    Returns an array [r, g, b]. Works also with shorthand hex triplets such as "#03F".

    const hexToRgb = hex =>
      hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
                 ,(m, r, g, b) => '#' + r + r + g + g + b + b)
        .substring(1).match(/.{2}/g)
        .map(x => parseInt(x, 16))
    
    console.log(hexToRgb("#0033ff")) // [0, 51, 255]
    console.log(hexToRgb("#03f")) // [0, 51, 255]

    Bonus: RGB to hex using padStart() method

    const rgbToHex = (r, g, b) => '#' + [r, g, b]
      .map(x => x.toString(16).padStart(2, '0')).join('')
    
    console.log(rgbToHex(0, 51, 255)); // '#0033ff'

    Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.

提交回复
热议问题